0

This is a difficult question to google!

I have an extension method that takes "Enum" as a parameter.

    public static T GetEntry<T>(this Dictionary<Enum, string> dictionary, Enum key)
    {
        string val;
        if (dictionary.TryGetValue(key, out val))
        {
            return (T)Convert.ChangeType(val, typeof(T));               
        }
        return default(T);
    }

but when I try to use it with a declared enum the compiler can't find the extension method

Dictionary<CmdAttr, String> Attributes;
cmd.CommandText.Attributes.GetEntry<double>(CommandText.CmdAttr.X);

Any idea how to make this work other than to declare the dictionary as

Dictionary<Enum, String> Attributes

which works but kind of defeats the point in having a declared enum?

Many Thanks

Anders Forsgren
  • 10,827
  • 4
  • 40
  • 77

2 Answers2

1

You can't do it exactly like you want to, because individual enums are not subclasses of Enum. But although this code isn't as pretty as you'd like, it's hardly ugly, and it works as you'd like:

// MyTestEnum.cs

enum MyTestEnum
{
    First,
    Second,
    Third
}

// Extensions.cs

static class Extensions
{
    public static TResult GetEntry<TEnum, TResult>(this Dictionary<TEnum, string> dictionary, TEnum key)
    {
        string value;
        if (dictionary.TryGetValue(key, out value))
        {
            return (TResult)Convert.ChangeType(value, typeof(TResult));
        }
        return default(TResult);
    }
}

// most likely Program.cs

void Main()
{
    Dictionary<MyTestEnum, string> attributes = new Dictionary<MyTestEnum, string>();
    attributes.Add(MyTestEnum.First, "1.23");

    // *** here's the actual call to the extension method ***
    var result = attributes.GetEntry<MyTestEnum, double>(MyTestEnum.First);

    Console.WriteLine(result);
}
Richard Irons
  • 1,433
  • 8
  • 16
-1

What you would like to do is (the following is not valid C# code):

public static T GetEntry<T,U>(this Dictionary<U, string> dictionary, U key) where U : Enum
{
    // your code
}

This will not compile (Constraint cannot be special class 'Enum'). So you have to look for alternatives. There are some good answers to this question. The most easy way would be to use where U : struct, IConvertible

Community
  • 1
  • 1
Fabian S.
  • 909
  • 6
  • 20
  • this is basically taking CodeCaster's and my comment and combining them to an answer. However, your answer could be and should be more complete. – Zohar Peled Apr 05 '16 at 08:31
  • @ZoharPeled You are welcome to suggest how to make my answer more complete. – Fabian S. Apr 05 '16 at 08:56