title: C# - Returning an Enum? from a static extension method
body: <p>I've added some extension methods for strings to make working with some custom enums easier.</p>
  
  <pre><code>public static Enum ToEnum&lt;T&gt;(this string s)
  {
      return (Enum)Enum.Parse(typeof(T), s);
  }
  
  public static bool IsEnum&lt;T&gt;(this string s)
  {
      return Enum.IsDefined(typeof(T), s);
  }
  </code></pre>
  
  <p>Note -- because of limitations of generic type constraints, I have to write the methods like the above.  I would love to use T ToEnum(this string s) where T: Enum to avoid the cast after making the call ... but no can do.</p>
  
  <p>In any event, I figured it would be nice to extend this concept a little bit to return Enum? in those instances where a method signature can accept various nullable enums.</p>
  
  <pre><code>public static Enum? ToEnumSafe&lt;T&gt;(this string s)
  {
      return (IsEnum&lt;T&gt;(s) ? (Enum)Enum.Parse(typeof(T), s) : null);
  }
  </code></pre>
  
  <p>However, this is a no-go due to compiler errors.</p>
  
  <pre><code>error CS0453: The type 'System.Enum' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'System.Nullable&lt;T&gt;'
  </code></pre>
  
  <p>I have to admit I'm a bit confused here as Enum? should be a legitimate return value, no?.  I tried something similar, but end up with the same error.</p>
  
  <pre><code>public static T? ToEnumSafe&lt;T&gt;(this string s)
  {
      return (IsEnum&lt;T&gt;(s) ? (T)Enum.Parse(typeof(T), s) : null);
  }
  </code></pre>
  
  <p>I even decided to rewrite the methods to remove the generics and I get more of the same:</p>
  
  <pre><code>public static bool IsEnum(this string s, Type T)
  {
      return Enum.IsDefined(T, s);
  }
  public static Enum? ToEnumSafe(this string s, Type T)
  {
      return (IsEnum(s, T) ? (Enum)Enum.Parse(T, s) : null);
  }
  </code></pre>
  
  <p>Am I missing something really stupid here?</p>