I have following code that does not work due to “a” being a value typed. But I thought it would not work even without accessors, but it did:
class Program
{
a _a //with accessors it WONT compile
{
get;
set;
}
static void Main(string[] args)
{
Program p = new Program();
p._a.X = 5; //when both accessors are deleted, compiler does not
//complain about _a.X not being as variable
}
}
struct a
{
public int X;
}
It does not work as “a” is struct. But when I delete accessors from “_a” instance, it works. I do not understand why.
Thanks
The main feature of value types is that they are copied rather than being passed by reference.
When you have a value type, and an accessor, you essentially have a value type being returned from a method, which causes a copy (the following two examples are the same):
If you now assign to the returned value, you’re assigning to a copy of x. So any changes made to the value returned from the property will be immediately lost.
When you remove the { get; } accessor, you’ve now got a basic field, e.g.:
or
Which means no copy is made, which means when assigning to the field, you’re no longer assigning to a copy.