Thursday 15 December 2016

c# - Enum as a parameter in a method, looping through the enum produces invalid cast




This is what I have:



    private IEnumerable GetAllEnumValues(Enum enumValues)
{
var allEnumValues = new List();
var values = Enum.GetValues(enumValues.GetType());
foreach (var selectedItem in values)
{
allEnumValues.Add(new SelectListItem
{

Value = ((int)selectedItem).ToString(),
Text = selectedItem.ToString()
});
}

return allEnumValues.AsEnumerable();
}


This is how the method is called:




AllAgencies = GetAllEnumValues((AgencyCodes) 0)


Build is fine, but when the method is actually used, I get "Specified cast is not valid." yellow screen of death on the .Add line. I need the Value of the SelectListItem to be the actual enum number, just casted to string. So far I tried all of these:
C# Iterating through an enum? (Indexing a System.Array), Enum in C# and foreach, How do I enumerate an enum? and in the end I always end up with the same error. I'm using .NET 4.0.


Answer



That usually means that your enum is not based on int, for example:



enum AgencyCodes : short {

...
}


You can't unbox an enum to the wrong type of value.


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...