I searched around and couldn't find any examples doing this, though this was helpful:
Create Generic method constraining T to an Enum
I have a generic function which wraps a function in an API (which I can't touch). The wrapped function takes a System.Enum and returns the same. My generic version simplifies the things quite a bit in the non-stripped down version of this example.
The problem is, I couldn't case from T to System.Enum, or back again, since T isn't constrained to System.Enum (at least that is my understanding).
The following code works but I am curious to know if there are any hidden traps, or better ways, since I am very new to generics:
using System
using System.Collections.Generic
...
public T EnumWrapper<T>(T enumVar) where T : struct, IFormattable, IConvertible, IComparable
{
if (!typeof(T).IsEnum)
throw new ArgumentException("Generic Type must be a System.Enum")
// Use string parsing to get to an Enum and back out again
Enum e = (Enum)Enum.Parse(typeof(T), enumVar.ToString());
e = WrappedFunction(e);
return (T)Enum.Parse(typeof(T), e.ToString());
}
If this is ok, then let this serve as an example. I couldn't find this and at the very least it is a working work-around.
P.S. Performance isn't an issue in this case. thought I was thinking string-work might be slow and I am always interested in performance tips.