Reputation: 443
I know there are approximately 1,000 questions on the C# struct. I want to iterate I understand the value semantics, the performance benefits of stackallocs, etc. My specific question stems from this msdn article on when to use a struct over a class. MSDN struct vs class C#
First, they speak to the benefit of inline data for containers, specifically arrays. One allocation, and the un-user-definable default initialization of all structs in the array. However, they also emphasize that structs should be immutable.
If I declare a mystuct[] s = new mystruct[16];
, I have 16 mystruct
s with default values inline. If I have created a 'kosher' struct with no external mutability as recommended, how is the construct of any use to me? I doubt I intend to have an array of 0-integrals and nulls exclusively.
Do they mean immutable when functioning as a record or a property return only, ie singular data transport?
If the specific conflict between default array initialization, and recommended immutability has been broached before, please mark as a duplicate. Thanks for any insight.
Upvotes: 1
Views: 1667
Reputation: 7111
The immutability being talked about is via the struct's methods, not the value of the struct itself. An instance of a struct can always be mutated through assignment - think of the integer loop variable in a for loop; it gets changed on each pass through the loop.
But, it wouldn't make sense for the framework's System.Int32
struct (i.e., int
) to have a DoubleIt
method that causes the underlying integer to have its value doubled without some obvious assignment operation (like how ++i;
is actually i=i+1;
).
Consider the difference between string.Replace
and StringBuilder.Replace
. The System.String
class is immutable. The Replace method on a string returns a new string instance that represents the original string after the replacement operation. StringBuilder's Replace does the replacement in place, mutating the internal object.
So, if i create an integer array:
var ar = new int[] {1, 2, 3, 4};
I can alway mutate the contents of that array (a System.Array instance, a reference type) by array assignment:
ar[2] = 200;
What would make no sense would be to call some mutating method on that (integer) array element.
Upvotes: 1
Reputation: 82474
There is no actual contradiction between the two:
after you do var s = new mystruct[16];
, it's true that you have and array of 16 instances of mystruct
initialized to the default value.
However, doing s[0] = new mystruct(<arguments list here>)
does not mutate the struct at the first cell of the array, it replaces it with the new struct.
So the struct it self is still immutable.
Upvotes: 1