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?
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.
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.
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.
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>()
.
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
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With