Skip to content

Ease Parsing enums in C# using generics

Once constant annoyance I’ve had with C# has been parsing a string into an enum.

Original C#:

MyEnum e = (MyEnum) Enum.Parse(typeof(MyEnum), "myvalue");

Using generics let you write a function to help:

public static T ParseEnum<T>(string name) {   
  return (T)Enum.Parse(typeof(T), name); 

So then you can simply* say:

MyEnum e = ParseEnum<MyEnum>("myvalue");

A little nicer, but still annoying.
*: simply for C#