.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!


.Net Generics – 1

Parsing an Enum:

Generally for converting a value to a type of Enum, we use the Enum.Parse method. Let’s take the following Enum for example and see how a value is converted.

enum Colour : int
  Red = 1,
  Blue = 2,
  Orange = 3

// Value read from the a source e.g., database.
int colourValue = 2;
//Convert the value to the type of Colour.
Colour colour = (Colour)Enum.Parse(typeof(Colour), 

All places where a value needs to be converted would have the above statement, where type of enum needs to be provided and the result needs to be casted back to the actual type. Using a simple Generics construct the same piece of code could be re-written as,

//Convert to the type of colour.
Colour colour = TEnum.Parse<Colour>(colourValue.ToString());


Here is the definition of TEnum

public struct TEnum
  public static T Parse<T>(string value)
    return Parse(value, true);

  public static T Parse<T>(string value, bool ignoreCase)
    return (T)Enum.Parse(typeof(T), value, ignoreCase);

That’s TEnum!