Jop
Jop

Reputation: 1035

Help with Enum extension methods

I have enum helper generic class where i have method EnumDescription() To call it i have to go like that EnumHelper<Enumtype>.EnumDescription(value) I want to implement enum extension method EnumDescription(this Enum value) which based on my enum helper method EnumHelper<T>.EnumDescription(value)

There one thing I am stuck with. Here is my code:

public static string EnumDescription(this Enum value)
{
    Type type = value.GetType();

    return EnumHelper<type>.EnumDescription(value); //Error here
}

I am getting an error The type or namespace name 'type' could not be found (are you missing a using directive or an assembly reference?)

Is there anything I can do to make it work?

Upvotes: 2

Views: 822

Answers (2)

LukeH
LukeH

Reputation: 269368

Two options that I can think of (there may be more).

First option: make the extension method generic. C# doesn't allow enum as a generic constraint, which means that you'll need a runtime check to ensure that the type is, in fact, an enum.

public static string EnumDescription<T>(this T value)
    where T : struct, IComparable, IConvertible, IFormattable
{
    if (!typeof(T).IsEnum)
        throw new InvalidOperationException("Type argument T must be an enum.");

    return EnumHelper<T>.EnumDescription(value);
}

Second option: use reflection. This will be slow(er), although you could create a delegate from the MethodInfo and cache it for re-use in a Dictionary<Type, Delegate> or similar. That way you'd only incur the cost of reflection the first time that particular type was encountered.

public static string EnumDescription(this Enum value)
{
    Type t = value.GetType();
    Type g = typeof(EnumHelper<>).MakeGenericType(t);
    MethodInfo mi = g.GetMethod("EnumDescription");
    return (string)mi.Invoke(null, new object[] { value });
}

Upvotes: 3

SLaks
SLaks

Reputation: 887453

Generics are done at compile-time.

You can either change your method to a generic method where T : struct or call the inner method using Reflection.

Upvotes: 1

Related Questions