-3

I'm trying to make an extension method that can apply to all/any enum, that returns the string constants of the enum as a list of strings.

this did not work.

static class EnumEx
{
    public static List<string> ToList(this System.Enum e)
    {
        return System.Enum.GetNames (e.GetType()).ToList();
    }
}

I'm calling it like:

public enum TestEnum { HELLO, WORLD };

foreach(string e in TestEnum.ToList())
    Console.Writeline(e);

UPDATE:

TestEnum instance = new TestEnum();
foreach(string e in instance.ToList())
        Console.Writeline(e);

and get the errors:

Type string[]' does not contain a memberToList' and the best extension method overload EnumEx.ToList(this System.Enum)' has some invalid arguments Extension method instance typestring[]' cannot be converted to `System.Enum'

user2994682
  • 503
  • 1
  • 8
  • 19

1 Answers1

3

When using extension methods, you need an instance on which to call that method. Using your method, you can do this:

var instance = new System.ConsoleModifiers();
Console.WriteLine(instance.ToList().Count());

If you want more information about why C# doesn't support static extension methods, you can read about that here: https://stackoverflow.com/a/4914207/573218

Community
  • 1
  • 1
John Koerner
  • 37,428
  • 8
  • 84
  • 134
  • Hehe, I didn't even know you could 'new' up an `Enum`. It's too bad you can't add custom methods to an `Enum` derived type. That's the only feature Java has that I wish C# had. – fourpastmidnight Jul 28 '14 at 01:53
  • Oh I see, extension methods can only be called on instances. But I'm still receiving errors listed above. – user2994682 Jul 30 '14 at 04:47