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
}
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;
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; }
}
}
}
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