Unboxed Solutions Blog The frenetic soapbox

Jul 30

Sean

Mutable Structs = Bad

  • Created: Friday, July 30, 2004
  • Sean

Several blogs I've read have made this point, but here's some easy to understand sample code that shows why...

 

struct Foo

{

    public int x;

    public void Set(int a) {this.x = a;}

}

 

class App

{

      [STAThread]

      static void Main(string[] args)

      {

        ArrayList list = new ArrayList();

        list.Add(new Foo());

        ((Foo)list[0]).Set(5);

 

        //Will print 0, not 5

        Console.WriteLine(((Foo)list[0]).x);

 

      }

}

 

Courtesy of Anders Hejlsberg
http://msdn.microsoft.com/msdntv/episode.aspx?xml=episodes/en/20040624csharpah/manifest.xml

;