Search code examples
c#structvariable-assignment

Assignment of fields/properties in a struct


Possible Duplicate:
Modify Struct variable in a Dictionary

Why is it that

  MyStruct test = new MyStruct();
  test.Closed = true;

Works great, but

MyDictionary[key].Closed = true;

Shows a "Cannot modify the expression because it is not a variable" error at compile time?

Why is different about the assignment in these two cases?

Note: MyDictionary is of type <int, MyStruct>

Code for the struct:

public struct MyStruct
{
    //Other variables
    public bool Isclosed;
    public bool Closed
    {
        get { return Isclosed; }
        set { Isclosed = value; }
    }
//Constructors
}

Solution

  • Because MyDictionary[key] returns a struct, it is really returning a copy of the object in the collection, not the actual object which is what happens when you use a class. This is what the compiler is warning you about.

    To work around this, you'll have to re-set MyDictionary[key] after the changes to the object, perhaps like this:

    var tempObj = MyDictionary[key];
    tempObj.Closed = true;
    MyDictionary[key] = tempObj;