0

I am trying to store a Enum class Type as value in Dictionary but i am getting 'Test' is a type, which is not valid in the given context. basically Test is Enum Class.

public enum Test
    {
        Test1 = 1,
        Test2 = 2,
    }

and Dictionary:-
private Dictionary<int, Type> _typeMapping;

Arvind
  • 53
  • 9
  • 2
    Maybe you need `typeof(Test)`? – Sweeper Sep 13 '19 at 06:29
  • How are you trying to add the enum to the dictionary? – Luaan Sep 13 '19 at 06:32
  • _typeMapping.Add(1,Test) – Arvind Sep 13 '19 at 06:32
  • 1
    Apart from the `and Dictionary:-` there is nothing wrong with the code in you question https://sharplab.io/#v2:EYLgHgbALANAJiA1AHwAICYCMBYAUKgBgAJVMoBuPPVAZhPSIGE8BvPIjogBwCcBLAG4BDAC4BTIgBE+AYxF8A9gDshPAJ4AePkpEwiAFTVcxAPiIB9EUbEBZIVy7aA5pVyci7TrRJQiNgBQAlJ4cbG6cAL54UbjUdGJKAK4AtgZiAM4iIURh7u76GSKYRAC8RJgw2fmFDGXoleEcMUA – Jodrell Sep 13 '19 at 06:37
  • 1
    Personally I don't think you need to save the Type, you can look up the Name of the Enum by Value, so you only need a List: https://stackoverflow.com/a/14971637/495455 – Jeremy Thompson Sep 13 '19 at 06:45
  • Actually i have to map a list of Enum. – Arvind Sep 13 '19 at 07:07
  • 1
    @Arvind If that is what you need to do show that code and perhaps we can help you to do it in a better way. – Magnus Sep 13 '19 at 08:16

2 Answers2

1

I would guess you are doing something like this:

_typeMapping.Add(1, Test);

When you should do this:

_typeMapping.Add(1, typeof(Test));
Tim Rutter
  • 4,549
  • 3
  • 23
  • 47
0

Solution:

class Program
{
    private static Dictionary<int, Type> TypeMapping { get; set; }
    static void Main(string[] args)
    {
        TypeMapping = new Dictionary<int, Type>();
        Test test1 = Test.Test1;
        TypeMapping.Add((int)test1, test1.GetType());
    }
}

public enum Test
{
    Test1 = 1,
    Test2 = 2
}
Marco Salerno
  • 5,131
  • 2
  • 12
  • 32