I have a little problem, I can’t modify property of structure that is stored in another property and I have no idea why:
Code:
public struct InfoProTile
{
public string Nazev { get; set; }
public double Hodnota { get; set; }
public TypValue TypValue { get; set; }
public NavigovatNa NavigovatNa { get; set; }
}
public InfoProTile BNDTileInfo { get { return bndTileInfo; } set { bndTileInfo = value; } } private InfoProTile bndTileInfo;
LoadModel()
{
...
BNDTileInfo = new InfoProTile();
BNDTileInfo.NavigovatNa = NavigovatNa.MainPage;
}
Error:
Error: Error 3 Cannot modify the return value of '...ViewModel.TilesModel.BNDTileInfo' because it is not a variable
I don’t get it because if I just change it into:
bndTileInfo.NavigovatNa = NavigovatNa.MainPage;
It works. Can anyone please explain it to me?
A
structis a value type, thus when you access it from a property, you are getting back a copy of thestructand not the underlying field direclty. Thus, C# won’t let you modify that copy of the struct because that is just a temporary object that will be discarded.So, when you call:
It first calls the
geton the property and returns a copy ofbndTitleInfo, and then attempts to set theNavigovatNaproperty and the copy. C# gives you the error here because that is not something you really want to do and thus is protecting you from yourself.But, when you call:
You are referencing the field directly and thus no copy is made and there is no compiler issue.
The long and the short of it is that mutable value types don’t make good properties (and in general you should avoid mutable value types completely).
To rectify, you can either make it a reference type (
class) or you can make yourstructimmutable, which would mean you’d have to assign a whole new struct instance to change it’s value.If you look at MSDN’s recommendations, in general
structis best suited to small, logical-single-value, immutable constructs: Choosing Between Classes and Structures