Download sample code |
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 { NORTH, EAST, WEST, SOUTH }
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.
No comments:
Post a Comment