开发者

Should structs always be immutable?

I was reading a couple of threads on here about structs and there is/was one about structs and how they should be representing immutable values (eg like a digit - 1) because of their value type behaviour/semantics.

But on the other hand, structs represent things like phone numbers, which can change 开发者_StackOverflowfor the same household.

Is this a hard and fast rule?


A phone number does not change; you just get a different one and discard the old one. The old one is still the same it always was. Same with dates, numbers, etc. - think of this when approaching structs. They are a way to encapsulate a value - which simply is; not the usage of the value, which changes.


Yes, structs should always be immutable! Mutable structs can cause terrible headaches as their usage can create very strange behavoir.


Yes, structs should almost always be immutable. For example, in your phone number case, the phone number itself doesn't mutate: what happens is that the household is allocated a new phone number. The phone number 555-555-1234 is still the phone number 555-555-1234, but the household's phone number is the different number 555-555-5678.

Note that you can find violations of this guideline in the .NET Framework. For example, the WPF Point and Size structs are mutable. This is not a good practice to follow, as one finds out when one tries to write something.Location.X = newX.


Immutable value != Immutable variable

What I means is, even if your variable contains a value that can't be changed, you can still change your variable to have different contents. int x = 5; x++; is legal. 5++; is not.

If your struct contains an integer, and you assign a new value to that integer (e.g. myStruct.MyInt++. you might think you are changing the value of MyInt. Really, you're storing a new value that's one greater than the old value.

Why does it matter? Because there might be another thread accessing myStruct.MyInt concurrently, and you don't want the value it's working with to suddenly change int the middle of being used.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜