How to convert string to enum

I recently was faced with a problem. Given a month name (e.g. January), provide its corresponding month number.

Here's an approach that I took, which works very well:

enum Months {
  January = 1,
  February,
  March,
  April,
  May,
  June,
  July,
  August,
  September,
  October,
  November,
  December,
}
 
public static int GetMonthNumber (string monthName) {
  Months month = (Months)Enum.Parse(typeof(Months), monthName, true);
  return (int)month;
}

In the enum definition, we put January = 1 to make sure that our enum starts with index 1 as opposed to 0.

Comments