One of the main advantages of value types, such as Rectangle
, is that if you have n storage locations of type Rectangle
, you can be sure that there are n instances of type Rectangle
. If you have a MyArray
array of type Rectangle
with a length of at least two, then an operator like MyArray[0] = MyArray[1]
will copy the fields MyArray[1]
into the tags MyArray[0]
, but they will continue to refer to different Rectangle
instances. If then the line of the operator MyArray[0].X += 4
is executed, which will change the X
field of one instance, without changing the X
value of any other slot in the array or Rectangle
instance. Notice, by the way, that creating an array instantly fills it with writable Rectangle
instances.
Imagine that a Rectangle
is a type of mutable type. Creating an array of mutable Rectangle
instances requires that one of them first evaluate the array and then assign a new Rectangle
instance to each element of the array. If you wanted to copy the value of one instance of the rectangle to another, you would have to say something like MyArray[0].CopyValuesFrom(MyArray[1])
[which, of course, would fail if MyArray[0]
not populated with a link to the new instance). If you accidentally say MyArray[0] = MyArray[1]
, writing to MyArray[0].X
will also affect MyArray[1].X
. Unpleasant stuff.
It is important to note that in C # and vb.net there are several places where the compiler will implicitly copy the value type, and then act on the copy as if it were the original. This is a very bad language design and has prompted some people to suggest that value types should be immutable (since most situations involving implicit copying only cause problems with mutable value types). Back when compilers were very bad at preventing cases where semantically questionable copies led to broken behavior, such a concept could be reasonable. This should be considered obsolete today, although given that any worthy modern compiler will flag errors in most scenarios where implicit copying will result in fuzzy semantics, including all scenarios where structures are only mutated through constructors, property definition tools, or external assignments for publicly mutable fields, An expression of type MyArray[0].X += 5
is more readable than MyArray[0] = new Rectangle(MyArray[0].X + 5, MyArray[0].Y, MyArray[0].Width, MyArray[0].Height)
.
source share