title: What is the best way to strictly parse string to enum?
body: <p>Let's say I have an enum:</p>
  
  <pre><code>public enum MyEnum
  {
      OptionOne = 0,
      OptionTwo = 2,
      OptionThree = 4
  }
  </code></pre>
  
  <p>Like it was said in the <a href="https://stackoverflow.com/questions/16100/how-do-i-convert-a-string-to-an-enum-in-c">How should I convert a string to an enum in C#?</a> question, I parse enum from string, using <code>Enum.Parse</code> method:</p>
  
  <pre><code>public class Enumer
  {
      public static MyEnum? ParseEnum(string input)
      {
          try
          {
              return (MyEnum) Enum.Parse(typeof (MyEnum), input);
          }
          catch (ArgumentException)
          {
              return null;
          }
      }
  
  }
  </code></pre>
  
  <p>Unfortunately, it doesn't work as expected with integer numbers, represented as strings.<br>
  <strong>I do not expect Parse.Enum() to convert int from string, but actually it does.</strong><br>
  A simple test:</p>
  
  <pre><code>[TestClass]
  public class Tester
  {
      [TestMethod]
      public void TestEnum()
      {
          Assert.AreEqual(MyEnum.OptionTwo, Enumer.ParseEnum("OptionTwo"));
          Assert.IsNull(Enumer.ParseEnum("WrongString"));
          Assert.IsNull(Enumer.ParseEnum("2")); // returns 2 instead of null
          Assert.IsNull(Enumer.ParseEnum("12345")); // returns 12345 instead of null
      }
  }
  </code></pre>
  
  <p>Only two checks of four can be passed.<br>
  <code>Enumer.ParseEnum("2")</code> returns <code>MyEnum.OptionTwo</code> instead of <code>null</code>.<br>
  Moreover, <code>Enumer.ParseEnum("12345")</code> returns 12345, regardless it's out of the scope.</p>
  
  <p>What is the best way to parse:</p>
  
  <ol>
  <li>Only string values of "MyEnum.OptionOne", "MyEnum.OptionTwo", "MyEnum.OptionThree" into their enum counterparts.</li>
  <li>Strings "MyEnum.OptionOne", "MyEnum.OptionTwo", "MyEnum.OptionThree" AND the values of 0, 2 and 4 into MyEnum.OptionOne, MyEnum.OptionTwo, MyEnum.OptionThree respectively?</li>
  </ol>
  
  <p>The link to the similar question <a href="https://stackoverflow.com/questions/16100/how-do-i-convert-a-string-to-an-enum-in-c">How should I convert a string to an enum in C#?</a> doesn't help with the test provided - it still converts strings as integers, even when they are out of the enum scope.</p>