Tuesday, 25 March 2008

Singleton pattern in C# 3.0

While I was going through some of the new features of C# 3.0, I thought why not implement Singleton pattern using automatic properties. Honestly, I hated declaring private fields and then encapsulate those vars in public properties. Automatic properties makes life easier and moreover a good readable code base with no cluttered private fields and public properties tied around.

The example shown below is an implementation of Singleton pattern in C# 3.0 specifically uses automatic properties.

public sealed class Singleton
{
public static Singleton Instance
{
get; private set;
}

static Singleton()
{
Instance = new Singleton();
}

private Singleton() { }

public void InstanceMethod()
{
Console.Write("Instance method invoked on type {0}", Instance.ToString());
Console.WriteLine("Are objects equal: {0} ", this == Instance);
}
}

Automatic properties: see the new feature and syntax in action. I have declared a static Instance property which doesn't use any underlying private field. The C# compiler takes care of generating the old style getter and setters. Note that I have used private access modifier for setter. A constraint on automatic properties is to define both get and set, otherwise the compiler will not be happy. Ok we can define that but I don't want my clients to use my setter, so I can specify the private access modifier and so only I can consume within the class scope.

No comments: