-1

The problem I'm having is creating the extension method!

public enum TestEnum
{
    One, Two, Three, Four
}

public static class EnumExtension
{
   public static bool TestMethod(this TestEnum e)
   {
       return false;
   }
}

[TestMethod]
public void TestAll()
{
    var result = TestEnum. ;   //this only gives the values of the enum (One, Two, Three, Four), there is no option to call the extension method
}

I hope the comment in the code above really shows the issue - I'm assuming I'm making a massive assumption and getting it very wrong.

I however would rather make this more usable, by allowing any enum to call this functionality. The end goal would be something like

public static IEnumerable<string> ConvertToList(this Enum e)
{
     var result = new List<string>();
     foreach (string name in Enum.GetNames(typeof(e)))    //doesn't like e
     {
         result.Add(name.ToString());
     }
     return result;
}
MyDaftQuestions
  • 4,487
  • 17
  • 63
  • 120
  • `TestEnum` is the type. You can do `TestEnum.One.TestMethod()`, or you can write a generic `EnumExtensions.TestMethod() ` – canton7 Apr 21 '19 at 11:58
  • @canton7, thank you for that, but please see my edit. The idea could be to convert any enum into a list of string. – MyDaftQuestions Apr 21 '19 at 11:59
  • 1
    Again you need to pass the type of enum, not one of its members. You can't do this as an extension method. – canton7 Apr 21 '19 at 12:02
  • 1
    You won't be able to get syntax like `EnumType.ExtensionMethod()`, it cannot be done. You have a couple of options, `EnumType.Value.ExtensionMethod()`, `Extensions.Something()` or `Extensions.Something(typeof(EnumType))`, none of which are significantly better than the existing `Enum.GetNames(typeof(EnumType))` method. Basically, you can't do it. – Lasse V. Karlsen Apr 21 '19 at 12:03
  • Might be helpful: https://stackoverflow.com/a/737940/6299857 – Prasad Telkikar Apr 21 '19 at 12:11
  • Thank you @PrasadTelkikar, if only it returned a List (which I can do) – MyDaftQuestions Apr 21 '19 at 12:13
  • `Enum.GetName()` returns array of string, you can convert it to `List` by `ToList()` function – Prasad Telkikar Apr 21 '19 at 12:18

2 Answers2

3

An extension method doesn't work on the type directly, but on a value of that type.

So something like

TestEnum Val = TestEnum One;
 var b = Val.TestMethod();
Hans Kesting
  • 38,117
  • 9
  • 79
  • 111
  • So, I can't convert the list of values associated with an `Enum` to a List as an extension method? I'm aware how I can get the code to work without extensions... – MyDaftQuestions Apr 21 '19 at 12:02
1

If you need list of all enums in List<string>, then you can try something like

List<string> enumList = Enum.GetNames(typeof(TestEnum)).ToList();

This will return list of string containing

  //"One", "Two", "Three", "Four"

enter image description here

Prasad Telkikar
  • 15,207
  • 5
  • 21
  • 44