Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cast<T>() with a Type variable

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

Here's 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 it is in fact declared in my method signature as MyMethod(Type enumType). I am not showing my method signature because that would require to introduce some struct I am using, which is not relevant to the problem here)

The problem is that this code does not compile and I am getting on the Cast<enumType>(). line the following error:

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

I don't understand how can enumType be unknown, I just declared it on the previous line!

Note that on the Enum.GetValues(enumType). line, there is no error flagged.

Am I missing something here? Is some LINQ playing tricks?

like image 561
Otiel Avatar asked Dec 15 '11 18:12

Otiel


People also ask

How do you cast a type?

Typecasting is making a variable of one type, such as an int, act like another type, a char, for one single operation. To typecast something, simply put the type of variable you want the actual variable to act as inside parentheses in front of the actual variable. (char)a will make 'a' function as a char.

How do you use type as variables?

For example: Type intType = typeof(Int32); object value1 = 1000.1; // Variable value2 is now an int with a value of 1000, the compiler // knows the exact type, it is safe to use and you will have autocomplete int value2 = Convert.

Which is used for casting of object to a type or a class?

Typecasting is the assessment of the value of one primitive data type to another type. In java, there are two types of casting namely upcasting and downcasting as follows: Upcasting is casting a subtype to a super type in an upward direction to the inheritance tree.


2 Answers

Generics don't allow you to pass an instance of a variable, you'll need to either use Cast<SomeEnum>(), or make the method where this code lies generic, and use something like Cast<T>().

like image 144
wsanville Avatar answered Sep 29 '22 06:09

wsanville


This 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 the Cast<T>() call. The generic method type needs the actual type specification (SomeEnum), not a System.Type (enumType).

like image 31
Reed Copsey Avatar answered Sep 29 '22 05:09

Reed Copsey