Readonly vs static readonly clarification2019 Community Moderator ElectionHow to properly access c++/CLI initonly TimeSpan field?What is the difference between const and readonly?Static readonly vs constWhy does Microsoft advise against readonly fields with mutable values?const, readonly and mutable value typesStruct containing reference typesConverting to int from string in public staticFilename pattern not working in OpenFileDialogStatic Readonly Fields and PerformanceMimicing constants using static readonly vs static getterStatic referenced in another .cs file

Can't make sense of a paragraph from Lovecraft

What are some noteworthy "mic-drop" moments in math?

How do spaceships determine each other's mass in space?

Do I really need to have a scientific explanation for my premise?

How many characters using PHB rules does it take to be able to have access to any PHB spell at the start of an adventuring day?

Getting the || sign while using Kurier

PTIJ: Why does only a Shor Tam ask at the Seder, and not a Shor Mu'ad?

Has a sovereign Communist government ever run, and conceded loss, on a fair election?

Called into a meeting and told we are being made redundant (laid off) and "not to share outside". Can I tell my partner?

Does an unused member variable take up memory?

Why is a very small peak with larger m/z not considered to be the molecular ion?

Does "Until when" sound natural for native speakers?

I can't die. Who am I?

What is the population of Romulus in the TNG era?

How do we create new idioms and use them in a novel?

What materials can be used to make a humanoid skin warm?

How to resolve: Reviewer #1 says remove section X vs. Reviewer #2 says expand section X

MySQL importing CSV files really slow

Why does Solve lock up when trying to solve the quadratic equation with large integers?

For which categories of spectra is there an explicit description of the fibrant objects via lifting properties?

Why is there an extra space when I type "ls" in the Desktop directory?

How to write a chaotic neutral protagonist and prevent my readers from thinking they are evil?

What are you allowed to do while using the Warlock's Eldritch Master feature?

Are small insurances worth it?



Readonly vs static readonly clarification



2019 Community Moderator ElectionHow to properly access c++/CLI initonly TimeSpan field?What is the difference between const and readonly?Static readonly vs constWhy does Microsoft advise against readonly fields with mutable values?const, readonly and mutable value typesStruct containing reference typesConverting to int from string in public staticFilename pattern not working in OpenFileDialogStatic Readonly Fields and PerformanceMimicing constants using static readonly vs static getterStatic referenced in another .cs file










6















I've run into an interesting situation I am trying to understand. I have a readonly struct field in my class. This means that when I reference it, it references a copy and not the actual one, so when I call a change method, it will be working with a copy, and the original will remain unchanged.



That is not what I am observing. I only see the expected behavior with a static field. I expected the behavior for both types.



private struct junk

public int i;

public void change()

i += 1;



private readonly junk jk;
private static readonly junk jk2;

public Form1()

InitializeComponent();
jk.change();
//jk.i is now 1, why? Shouldn't it be changing a copy and not the original jk?
jk2.change();
//jk2.i is 0










share|improve this question







New contributor




Endel_ is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.















  • 6





    Mutable value types - just say no.

    – Damien_The_Unbeliever
    6 hours ago







  • 3





    please get rid of the irrelevant call to InitializeComponent() and insert code that prints the values of jk.i and jk2.i and show us what it prints. We do not care to read what you think the values are, we want to see what the values are.

    – Mike Nakis
    6 hours ago






  • 2





    (And we also want to see what makes you think the values are what you claim they are.)

    – Mike Nakis
    6 hours ago






  • 2





    A warning would have been nice, but the C# compiler does not have the plumbing that can ensure that change() has an observable side-effect. A counter-example is the C++/CLI compiler, it always assumes and that doesn't make programmers happy either. Add static Form1() to see that it is allowed to mutate the jk2 value.

    – Hans Passant
    5 hours ago















6















I've run into an interesting situation I am trying to understand. I have a readonly struct field in my class. This means that when I reference it, it references a copy and not the actual one, so when I call a change method, it will be working with a copy, and the original will remain unchanged.



That is not what I am observing. I only see the expected behavior with a static field. I expected the behavior for both types.



private struct junk

public int i;

public void change()

i += 1;



private readonly junk jk;
private static readonly junk jk2;

public Form1()

InitializeComponent();
jk.change();
//jk.i is now 1, why? Shouldn't it be changing a copy and not the original jk?
jk2.change();
//jk2.i is 0










share|improve this question







New contributor




Endel_ is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.















  • 6





    Mutable value types - just say no.

    – Damien_The_Unbeliever
    6 hours ago







  • 3





    please get rid of the irrelevant call to InitializeComponent() and insert code that prints the values of jk.i and jk2.i and show us what it prints. We do not care to read what you think the values are, we want to see what the values are.

    – Mike Nakis
    6 hours ago






  • 2





    (And we also want to see what makes you think the values are what you claim they are.)

    – Mike Nakis
    6 hours ago






  • 2





    A warning would have been nice, but the C# compiler does not have the plumbing that can ensure that change() has an observable side-effect. A counter-example is the C++/CLI compiler, it always assumes and that doesn't make programmers happy either. Add static Form1() to see that it is allowed to mutate the jk2 value.

    – Hans Passant
    5 hours ago













6












6








6


1






I've run into an interesting situation I am trying to understand. I have a readonly struct field in my class. This means that when I reference it, it references a copy and not the actual one, so when I call a change method, it will be working with a copy, and the original will remain unchanged.



That is not what I am observing. I only see the expected behavior with a static field. I expected the behavior for both types.



private struct junk

public int i;

public void change()

i += 1;



private readonly junk jk;
private static readonly junk jk2;

public Form1()

InitializeComponent();
jk.change();
//jk.i is now 1, why? Shouldn't it be changing a copy and not the original jk?
jk2.change();
//jk2.i is 0










share|improve this question







New contributor




Endel_ is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.












I've run into an interesting situation I am trying to understand. I have a readonly struct field in my class. This means that when I reference it, it references a copy and not the actual one, so when I call a change method, it will be working with a copy, and the original will remain unchanged.



That is not what I am observing. I only see the expected behavior with a static field. I expected the behavior for both types.



private struct junk

public int i;

public void change()

i += 1;



private readonly junk jk;
private static readonly junk jk2;

public Form1()

InitializeComponent();
jk.change();
//jk.i is now 1, why? Shouldn't it be changing a copy and not the original jk?
jk2.change();
//jk2.i is 0







c#






share|improve this question







New contributor




Endel_ is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.











share|improve this question







New contributor




Endel_ is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.









share|improve this question




share|improve this question






New contributor




Endel_ is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.









asked 6 hours ago









Endel_Endel_

341




341




New contributor




Endel_ is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.





New contributor





Endel_ is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.






Endel_ is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.







  • 6





    Mutable value types - just say no.

    – Damien_The_Unbeliever
    6 hours ago







  • 3





    please get rid of the irrelevant call to InitializeComponent() and insert code that prints the values of jk.i and jk2.i and show us what it prints. We do not care to read what you think the values are, we want to see what the values are.

    – Mike Nakis
    6 hours ago






  • 2





    (And we also want to see what makes you think the values are what you claim they are.)

    – Mike Nakis
    6 hours ago






  • 2





    A warning would have been nice, but the C# compiler does not have the plumbing that can ensure that change() has an observable side-effect. A counter-example is the C++/CLI compiler, it always assumes and that doesn't make programmers happy either. Add static Form1() to see that it is allowed to mutate the jk2 value.

    – Hans Passant
    5 hours ago












  • 6





    Mutable value types - just say no.

    – Damien_The_Unbeliever
    6 hours ago







  • 3





    please get rid of the irrelevant call to InitializeComponent() and insert code that prints the values of jk.i and jk2.i and show us what it prints. We do not care to read what you think the values are, we want to see what the values are.

    – Mike Nakis
    6 hours ago






  • 2





    (And we also want to see what makes you think the values are what you claim they are.)

    – Mike Nakis
    6 hours ago






  • 2





    A warning would have been nice, but the C# compiler does not have the plumbing that can ensure that change() has an observable side-effect. A counter-example is the C++/CLI compiler, it always assumes and that doesn't make programmers happy either. Add static Form1() to see that it is allowed to mutate the jk2 value.

    – Hans Passant
    5 hours ago







6




6





Mutable value types - just say no.

– Damien_The_Unbeliever
6 hours ago






Mutable value types - just say no.

– Damien_The_Unbeliever
6 hours ago





3




3





please get rid of the irrelevant call to InitializeComponent() and insert code that prints the values of jk.i and jk2.i and show us what it prints. We do not care to read what you think the values are, we want to see what the values are.

– Mike Nakis
6 hours ago





please get rid of the irrelevant call to InitializeComponent() and insert code that prints the values of jk.i and jk2.i and show us what it prints. We do not care to read what you think the values are, we want to see what the values are.

– Mike Nakis
6 hours ago




2




2





(And we also want to see what makes you think the values are what you claim they are.)

– Mike Nakis
6 hours ago





(And we also want to see what makes you think the values are what you claim they are.)

– Mike Nakis
6 hours ago




2




2





A warning would have been nice, but the C# compiler does not have the plumbing that can ensure that change() has an observable side-effect. A counter-example is the C++/CLI compiler, it always assumes and that doesn't make programmers happy either. Add static Form1() to see that it is allowed to mutate the jk2 value.

– Hans Passant
5 hours ago





A warning would have been nice, but the C# compiler does not have the plumbing that can ensure that change() has an observable side-effect. A counter-example is the C++/CLI compiler, it always assumes and that doesn't make programmers happy either. Add static Form1() to see that it is allowed to mutate the jk2 value.

– Hans Passant
5 hours ago












1 Answer
1






active

oldest

votes


















6















I have a readonly struct field in my class. This means that when I reference it, it references a copy and not the actual one, so when I call a change method, it will be working with a copy, and the original will remain unchanged.




That's not at all what the readonly modifier does. The readonly modifier prevents you from assigning a new value to jk anywhere but in a constructor. Then, the static modifier allows you to reuse that value independently of the instance of Form1 you are working with.

That said, neither readonly nor static is making the weird behavior you are describing because that exact behavior cannot be reproduced with the code you've posted.



Look at a simpler example in a Console application (which you can try here):



public class Program

private readonly junk jk;
private static readonly junk jk2;

public static void Main()

var program = new Program();
program.jk.change();
Console.WriteLine(program.jk.i); // prints 0

jk2.change();
Console.WriteLine(jk2.i); // prints 0



public struct junk

public int i;
public void change()

i += 1;




Then, as @Damien_The_Unbeliever commented, try to avoid mutable structs as much as you can.






share|improve this answer






















    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );






    Endel_ is a new contributor. Be nice, and check out our Code of Conduct.









    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55090417%2freadonly-vs-static-readonly-clarification%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    6















    I have a readonly struct field in my class. This means that when I reference it, it references a copy and not the actual one, so when I call a change method, it will be working with a copy, and the original will remain unchanged.




    That's not at all what the readonly modifier does. The readonly modifier prevents you from assigning a new value to jk anywhere but in a constructor. Then, the static modifier allows you to reuse that value independently of the instance of Form1 you are working with.

    That said, neither readonly nor static is making the weird behavior you are describing because that exact behavior cannot be reproduced with the code you've posted.



    Look at a simpler example in a Console application (which you can try here):



    public class Program

    private readonly junk jk;
    private static readonly junk jk2;

    public static void Main()

    var program = new Program();
    program.jk.change();
    Console.WriteLine(program.jk.i); // prints 0

    jk2.change();
    Console.WriteLine(jk2.i); // prints 0



    public struct junk

    public int i;
    public void change()

    i += 1;




    Then, as @Damien_The_Unbeliever commented, try to avoid mutable structs as much as you can.






    share|improve this answer



























      6















      I have a readonly struct field in my class. This means that when I reference it, it references a copy and not the actual one, so when I call a change method, it will be working with a copy, and the original will remain unchanged.




      That's not at all what the readonly modifier does. The readonly modifier prevents you from assigning a new value to jk anywhere but in a constructor. Then, the static modifier allows you to reuse that value independently of the instance of Form1 you are working with.

      That said, neither readonly nor static is making the weird behavior you are describing because that exact behavior cannot be reproduced with the code you've posted.



      Look at a simpler example in a Console application (which you can try here):



      public class Program

      private readonly junk jk;
      private static readonly junk jk2;

      public static void Main()

      var program = new Program();
      program.jk.change();
      Console.WriteLine(program.jk.i); // prints 0

      jk2.change();
      Console.WriteLine(jk2.i); // prints 0



      public struct junk

      public int i;
      public void change()

      i += 1;




      Then, as @Damien_The_Unbeliever commented, try to avoid mutable structs as much as you can.






      share|improve this answer

























        6












        6








        6








        I have a readonly struct field in my class. This means that when I reference it, it references a copy and not the actual one, so when I call a change method, it will be working with a copy, and the original will remain unchanged.




        That's not at all what the readonly modifier does. The readonly modifier prevents you from assigning a new value to jk anywhere but in a constructor. Then, the static modifier allows you to reuse that value independently of the instance of Form1 you are working with.

        That said, neither readonly nor static is making the weird behavior you are describing because that exact behavior cannot be reproduced with the code you've posted.



        Look at a simpler example in a Console application (which you can try here):



        public class Program

        private readonly junk jk;
        private static readonly junk jk2;

        public static void Main()

        var program = new Program();
        program.jk.change();
        Console.WriteLine(program.jk.i); // prints 0

        jk2.change();
        Console.WriteLine(jk2.i); // prints 0



        public struct junk

        public int i;
        public void change()

        i += 1;




        Then, as @Damien_The_Unbeliever commented, try to avoid mutable structs as much as you can.






        share|improve this answer














        I have a readonly struct field in my class. This means that when I reference it, it references a copy and not the actual one, so when I call a change method, it will be working with a copy, and the original will remain unchanged.




        That's not at all what the readonly modifier does. The readonly modifier prevents you from assigning a new value to jk anywhere but in a constructor. Then, the static modifier allows you to reuse that value independently of the instance of Form1 you are working with.

        That said, neither readonly nor static is making the weird behavior you are describing because that exact behavior cannot be reproduced with the code you've posted.



        Look at a simpler example in a Console application (which you can try here):



        public class Program

        private readonly junk jk;
        private static readonly junk jk2;

        public static void Main()

        var program = new Program();
        program.jk.change();
        Console.WriteLine(program.jk.i); // prints 0

        jk2.change();
        Console.WriteLine(jk2.i); // prints 0



        public struct junk

        public int i;
        public void change()

        i += 1;




        Then, as @Damien_The_Unbeliever commented, try to avoid mutable structs as much as you can.







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered 6 hours ago









        Camilo TerevintoCamilo Terevinto

        19k63767




        19k63767






















            Endel_ is a new contributor. Be nice, and check out our Code of Conduct.









            draft saved

            draft discarded


















            Endel_ is a new contributor. Be nice, and check out our Code of Conduct.












            Endel_ is a new contributor. Be nice, and check out our Code of Conduct.











            Endel_ is a new contributor. Be nice, and check out our Code of Conduct.














            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55090417%2freadonly-vs-static-readonly-clarification%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Are there any comparative studies done between Ashtavakra Gita and Buddhim?How is it wrong to believe that a self exists, or that it doesn't?Can you criticise or improve Ven. Bodhi's description of MahayanaWas the doctrine of 'Anatta', accepted as doctrine by modern Buddhism, actually taught by the Buddha?Relationship between Buddhism, Hinduism and Yoga?Comparison of Nirvana, Tao and Brahman/AtmaIs there a distinction between “ego identity” and “craving/hating”?Are there many differences between Taoism and Buddhism?Loss of “faith” in buddhismSimilarity between creation in Abrahamic religions and beginning of life in Earth mentioned Agganna Sutta?Are there studies about the difference between meditating in the morning versus in the evening?Can one follow Hinduism and Buddhism at the same time?Are there any prohibitions on participating in other religion's practices?Psychology of 'flow'

            fallocate: fallocate failed: Text file busy in Ubuntu 17.04? Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern)defragmenting and increasing performance of old lubuntu system with swap partitionIssue with increasing the root partition from the swapthis /usr/bin/dpkg returned error || ubuntu-16.04, 64bitDefault 17.04 swap file locationHow to Resize Ubuntu 17.04 Zesty Swap file size?Ubuntu freezes from online formsMy Laptop is not starting after upgrade ubuntu 16.04 (Kernel 4.8.0-38 to 04.10.0-36)hcp: ERROR: FALLOCATE FAILED!Not sure my swap is being usedWine 3.0 asking for more virtual free swap

            Where is the suspend/hibernate button in GNOME Shell? Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern)No suspend option in UI on Bionic BeaverHow can I set sleep mode in ubuntu18.04 LTS and what is the short cut key to do so?17.10 suspend not availableUbuntu 18.04 LTS missing sleep optionUbuntu 18.04 LTS - missing suspend option when power button is pressedHow to put Thinkpad X1 Extreme to sleep in Ubuntu 18.10?Suspend Button in interactive power button menu18.04 - Keep programs running after logging outway to disable Hibernate from within gconf-editor so button disappears?How can I hibernate from GNOME Shell?How can I hibernate/suspend from the command line and do so at a specific timeNo permission to suspend/hibernate after upgrading to 12.10MATE - Missing Suspend and Hibernate buttons, pressing power button shutdowns system immediatelyUbuntu 14.04: Suspend, Hibernate and Suspend-hybrid in the menu?Change “power-button-action” comand for “hibernate” option in GNOME 3.18Shutdown / Power off button does always go to suspend on 17.10Hibernate after suspend stopped working in 17.10Why doesn't the keyboard screenshot button work on Ubuntu with GNOME shell?