.Net Generics – 2

Generic Singleton Type

We have all writen Singleton implementations in our code sometime or the other. The basic code structure is the almost the same.  Have a static member of a type, check for null before initialization and return the instance. Additionally, lock the object if you need to have synchronization logic.  The same boiler plate code can be re-written using Generics so that it can be re-used.

public class TSingleton<TType>
        where TType:new()
        private static TType _instance;

        public static TType Instance
                if (_instance == null)
                    _instance = new TType();

                return _instance;

For example, let say we have classes called DBService and Logger which you would like to be a singleton’s. Using the above type, you can your singleton’s as,

DBService dbService = TSingleton<DBService>.Instance;
Logger logger = TSingleton<Logger>.Instance;

Thats TSingleton!


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s