I have a simple enum, that looks something like the following:
public enum Brand
{
[Description("Friendly Brand Name")]
Brand1,
[Description("Once Again")]
Brand2
} // eo enum Brand
I have an extension method with the following signature:
public static string ToDescription(this Enum self) { /* .. implementation .. */ }
A quick check in LINQPad shows me that:
Brand brand = Brand.Brand1;
brand.ToDescription().Dump();
... all works as intended.
Now comes the fun part. In my code, at this point I want to iterate through the values of an arbituary enum (in this case Brand
), and I've only got a System.Type
to go on. First, I implemented a quick extension method for Array
:
public static IEnumerable<object> AsEnumerable(this Array self)
{
foreach(object o in self)
yield return o;
} // eo AsEnumerable
Knowing that my type is an Enum
, I iterate through the values thusly (where type
is the actual Brand
enum type) (Note: CastTo
is just a shorthand extension method for Convert.ChangeType
):
foreach (var enumValue in Enum.GetValues(type).AsEnumerable().Select((e) => e.CastTo(type)))
Console.WriteLine(enumValue.ToDescription());
And I get the following runtime error:
'MyNameSpace.Brand' does not contain a definition for 'ToDescription'
Debugging, in the immediate window the type of enumValue
is indeed Brand
. I am guessing this may have something to do with the way extension methods work - or that I am missing something obvious. Perhaps there's a workaround?
I think your CastTo
just changes the type at runtime, why not use the Cast<T>
instead?
foreach (var enumValue in Enum.GetValues(type).Cast<Enum>())
Console.WriteLine(enumValue.ToDescription());
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments