Search code examples
c#propertiesstructfieldprimitive

C# Primitive types (double, int, etc) and Struct differences


I am confused with structs.

class A
{
  double a { get; set; }  
  MyStruct b { get; set; }

  void Modify()
  {
     a = 1.0;    // This compiles.
     b.c = 2.0;  // Assuming c is a double. This gives the known error.
  }
}

Now why I am able to set the value of the structure a, and not of the structure's field b ? The answer I read is that I have a copy of b and not b's backing field. By the same logic I must have a copy of a, not a, so how it explains that the a property is changed after the permitted assignement

a = 1.0;

? Thank you.

EDIT :
Also in order to still use b inside the A class, "filtered" by the set and get methods and not directly by using the backing field _b, something which could look like this:

MyStruct _b;
MyStruct b { get { return _b; } set { _b=value; } }

and then use the field

_b

, as correctly stated in the answers, I thinked of a silly method to "wrap" the property in an one dimensional array of size 1.

MyStruct[] b { get; set; }

kind of wrapping the struct with a class. I dont know the computational cost of this, but I preferred it from using the field directly inside the A class.

ANSWERED : Ok, the confusion in this question comes, when you are used to interpret properties as fields in your mind. If you interpret properties the correct way -as the MsIL does-, all things settle down. All the answers and comments below, are relevant. (Sorry for the bad English.)


Solution

  • You're doing two different things. Here's an example of doing the same thing in both places:

    a = 1.0;
    b = new MyStruct(2.0);
    

    In both of these cases, the assignment operator is calling the "setter" of the property. You can think of it as:

    this.SetA(1.0);
    this.SetB(new MyStruct(2.0));
    

    As a more complicated example, if you wrote:

    a = a + 1.0;
    

    that's equivalent to:

    this.SetA(1.0 + this.GetA());