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; set; }}struct Point{    public ...

Get C# 4.0 Unleashed now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.