Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assignment of fields/properties in a struct [duplicate]

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
}
like image 549
soandos Avatar asked Sep 02 '11 04:09

soandos


2 Answers

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], perhaps like this:

var tempObj = MyDictionary[key];
tempObj.Closed = true;
MyDictionary[key] = tempObj;
like image 168
Keith Avatar answered Oct 19 '22 10:10

Keith


Change the struct to be a class instead...

class Program
{
    static void Main(string[] args)
    {
        dic = new Dictionary<int, MyStruct>();

        MyStruct s = new MyStruct(){ Isclosed=false};

        dic.Add(1,s);

        dic[1].Isclosed = true;

        Console.WriteLine(dic[1].Isclosed.ToString()); //will print out true...
        Console.Read();
    }

    static Dictionary<int, MyStruct> dic;

    public class MyStruct
    {
        public bool Isclosed;
        public bool Closed
        {
            get { return Isclosed; }
            set { Isclosed = value; }
        }
    }
}
like image 43
Tono Nam Avatar answered Oct 19 '22 09:10

Tono Nam