Wednesday, July 18, 2012

String value to ENUM type conversion

Download sample code
An enumeration type (also named an enumeration or an enum) provides an efficient way to define a set of named integral constants that may be assigned to a variable. By using enum you can clearly specify for the client code which values are valid for variable.

Also in some cases we may come across storing the enum value in form of string value, which further needs to be converted to enum type so that business logic remains consistent and error free.

While converting string to enum type we can use Enum.Parse() or Enum.TryParse()independently wherever its required. Now this kills re-usability feature of OOP.

Taking advantage of re-usability I have created generic method which will be accepting string value and expected type of enum in form of template T.

Below is an extension method used to convert string to enum type, however instance methods can be created too.
public static T ToEnum<T>(this string value)
      if (string.IsNullOrEmpty(value) && typeof(T).IsEnum)
          bool result = false;
          Enum.TryParse(value, true, out result);

          if (result)
             return (T)Enum.Parse(typeof(T), value, true);

      //This will return default value as 0
      return default(T);

In above code T is the template which we are expecting. For demo purpose I have declared two enum types namely Colors and Direction which can be passed as template T.
public enum Colors
      RED = 0,
      GREEN = 1,
      BLUE = 2

public enum Direction

Invoking enum conversion method.
//Calling ToEnum conversion extension method            
Colors selectedColor = "red".ToEnum<Colors>();

Direction selectedDirection = "North".ToEnum<Direction>();

Thus “red” will be converted to its relevant enum value and stored in the enum type of variable which can be used same as that of normal variable in logic. And if at all specified string is not found in enum, it will return default “0” value.

Here values of variables "selectedColor" and "selectedDirection" would be "Colors.RED" and "Direction.NORTH" respectively.

As per sample application and code output text will be shown in red color.

Learn by diving in Programming Ocean...
Happy Programming!!!

No comments:

Post a Comment