.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), 
                         colourValue.ToString());

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!

Advertisements

One thought on “.Net Generics – 1

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s