The Dangers of Mutable Value Types

Being passed by value, there are some dangers associated with the use of value types, especially when they’re made mutable. In general, it’s a bad idea to allow mutation of structs; instead, simply create a new value instance and substitute the original value altogether. A good example of the problems that could arise when dealing with mutable value types is shown here:

using System;class Program{    static void Main()    {        var kid= new Kid();        Console.WriteLine(kid.Location.X + ", " + kid.Location.Y);        kid.Location.X = 3;        kid.Location.Y = 4;        Console.WriteLine(kid.Location.X + ", " + kid.Location.Y);    }}class Kid{    public Point Location { get; ...

Get C# 5.0 Unleashed now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.