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?
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.
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.
Structs and classes are not immutable by default, though it is a best practice to make structs immutable.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With