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"
}
Advertisements
This entry was posted in Computers en internet. Bookmark the permalink.

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