Parse strings as enum items

I wrote a helper function today that tries to parse strings as items of an enum. It’s very simple, but I think it’s beautiful. (Language: C#)

// Beautiful code
public static bool TryParseEnum<T>(string value, out T result) {
  if (Enum.IsDefined(typeof(T), value)) {
    result = (T)Enum.Parse(typeof(T), value);
    return true;
  }
  result = default(T);
  return false;
}

// Simple enum
public enum Status {
  unknown, good, bad
}

// Testing code
public void Main(){
  Status one, two;
  if (TryParseEnum("good", out one))
    Response.Write(one); // writes "good"
  TryParseEnum("excellent", out two); // returns false
  Response.Write(two); // writes "unknown"
}
This entry was posted in Computers en internet. Bookmark the permalink.

Leave a comment