Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

readonly changing the behavior of a struct

I'm trying to understand some basic concepts:

class Program
{
   private static readonly MyStruct m = new MyStruct();
   static void Main(string[] args)
    {
       //new MutableSample().RunSample();

       Console.WriteLine(m.ChangeInternal());
       Console.WriteLine(m.ChangeInternal());
       Console.WriteLine(m.ChangeInternal());
       Console.Read();
    }
}

public struct MyStruct
{
    private int x;
    public int ChangeInternal()
    {
        this.x = this.x + 1;
        return this.x;
    }
}

When I run this code it gives me 1, 1, 1, but when I remove the "readonly" it says 1, 2, 3.

Can someone explain to me this?

like image 301
Carloos Avatar asked Nov 03 '14 19:11

Carloos


People also ask

What is a readonly struct?

The readonly keyword is a C# modifier used to limit access to all the data members of a struct. If the readonly modifier is used in the declaration of a struct, then: The members of the struct are read-only. None of the members can have setters. A parameterized constructor is used to initialize the data members.

What is the best way to declare a method parameter that behaves as a readonly reference variable?

Declaring in parameters in parameters are declared by using in keyword as a modifier in the parameter signature. For all purposes the in parameter is treated as a readonly variable. Most of the restrictions on the use of in parameters inside the method are the same as with readonly fields.

Are structs immutable C#?

Structs and classes are not immutable by default, though it is a best practice to make structs immutable.

What is readonly C#?

Use the readonly keyword in C#The readonly keyword can be used to define a variable or an object as readable only. This means that the variable or object can be assigned a value at the class scope or in a constructor only.


1 Answers

Section 7.5.4 of the C# specs states:

[...] if the field is readonly and the reference occurs outside an instance constructor of the class in which the field is declared, then the result is a value, namely the value of the field I in the object referenced by E

So when the field is readonly you're mutating a copy (since it's impossible to mutate a value, only a variable). When it isn't you're mutating the field itself.

This is described in more detail in this blog post by Eric Lippert. To quote its ending:

This is yet another reason why mutable value types are evil. Try to always make value types immutable.

like image 56
Servy Avatar answered Oct 12 '22 23:10

Servy