I know the answer (it's 42)

A blog on coding, .NET, .NET Compact Framework and life in general....

September, 2006

Posts
  • I know the answer (it's 42)

    MyType.Empty

    • 5 Comments

    Many times it is common to have a class that has a very common object instance that is used at a lot of places. Like the empty string for the string class. In such cases its very convenient to keep such a pre-constructed object around for easy reference.

    This saves memory as the same reference can be used all-over. Even for strings where the same interned string is returned, it saves the time of trying to construct that object. It also saves the work of trying to figure out how to make that common instance.

    Examples of this pattern abound in the .NET framework. The most common being String.Empty which represents an empty "" string. The others are IntPtr.Zero, Color.Red (same as new Color(255,0,0);) and many more...

    This pattern is typically implemented as follows

    public class MyClass

    {

    int val;

    public int Val

    {

    get { return val; }

    set { val = value; }

    }

    public MyClass(int val)

    {

    this.val = val;

    }

    public MyClass() {}

    public static readonly MyClass Empty = new MyClass(0);

    }

    If you compile this code with Code Analysis (FxCop) enabled you'll get a security warning (CA2104) on the last line. The reason is that, since the class is not immutable one can write the following code

    MyClass.Empty.Val = 5;

    MyClass mc = MyClass.Empty;// get modified value

    Console.WriteLine(mc.Val); // prints 5 and NOT 0

    The first line changes the value for the Empty instance and all subsequent accesses get the changed value. This can be due to a bug or someone can easily use this as an attack to break a system. However if you remove the set accessor for the MyClass class then this threat goes away. String uses this pattern because strings are immutable.

    So the bottom line is that use this pattern only on immutable types.

    On a related note Color.Red or other such colors do not return a pre-constructed color. It creates and returns a new color and just provides an easy way to create a new standard color.

Page 1 of 1 (1 items)