Cast <T> () with a type variable

I am trying to make a method to list any enum by returning a list containing each name and constant value.

Here is my code:

Type enumType = typeof(SomeEnum); var enumConstants = Enum.GetValues(enumType). Cast<enumType>(). Select(x => new { Value = (int) x, Name = x.ToString() }); 

(I declare enumType in this snippet, but in fact it is declared in my method signature as MyMethod(Type enumType) . I do not show my method signature, because for this it will be necessary to enter some structure that I use does not apply to the problem here )

The problem is that this code does not compile, and I get Cast<enumType>(). in the line Cast<enumType>(). following error:

The type or namespace name 'enumType' cannot be found (are you missing the using directive or assembly references?)

I do not understand how enumType unknown, I just declared it in the previous line!

Notice that in the line is Enum.GetValues(enumType). no errors were noted.

Am I missing something? Are some LINQ tricks?

+7
source share
6 answers

Generics do not allow you to pass an instance of a variable, you need to either use Cast<SomeEnum>() , or make a method in which this code is shared, and use something like Cast<T>() .

+5
source

It should be:

 Type enumType = typeof(SomeEnum); var enumConstants = Enum.GetValues(enumType). Cast<SomeEnum>(). Select(x => new { Value = (int) x, Name = x.ToString() }); 

The problem is calling Cast<T>() . A generic method type requires the actual type specification ( SomeEnum ), not System.Type ( enumType ).

+5
source

Try the following:

  Type enumType = typeof(SqlDbType); var enumConstants = Enum.GetValues(enumType). Cast<Enum>(). Select(x => new { Value = Convert.ToInt32(x), Name = x.ToString() }); 
+2
source

Try to change

 Cast<enumType>() 

to

 Cast<SomeEnum>() 
+1
source

that's what i

 namespace SO.Enums { public enum SomeEnum { A, B, C, D } class Program { static void Main(string[] args) { Type enumType = typeof(SomeEnum); var enumConstants = Enum.GetValues(enumType). Cast<SomeEnum>(). Select(x => new { Value = (int)x, Name = x.ToString() }); } } } 
+1
source
 string[] names = Enum.GetNames(typeof(MyEnum)); MyEnum[] values = (MyEnum[])Enum.GetValues(typeof(MyEnum)); int[] intValues = values.Cast<int>().ToArray(); for (int i = 0; i < names.Length; i++) { Console.WriteLine("{0} = {1}", names[i], intValues[i]); } 

Or in a more concise way:

 var result = Enum.GetValues(typeof(MyEnum)) .Cast<MyEnum>() .Select(x => new { Name = Enum.GetName(typeof(MyEnum), x), Value = (int)x }); 
0
source

All Articles