Enum extension method to get all values

I want to do something like this:

enum MyEnum { None, One, Two };

var myEnumValues = MyEnum.Values();

      

My extension method:

        public static IEnumerable<T> Values<T>(this Enum enumeration)
             where T : struct
         => Enum.GetValues(typeof(T)).Cast<T>();

      

But it looks like this:

MyEnum.None.Values<MyEnum>(); 

      

How to do it?

+3


source to share


2 answers


Extension methods are static methods applied to an instance of an object.



MyEnum

is a type, not an instance, so you cannot add extension methods to it.

+3


source


How about such a design? It mimics the way enum works, but it has the ability to implement a method Values

:

public class WeatherType
{
    private readonly string name;

    public static readonly WeatherType Bad = new WeatherType("Bad");
    public static readonly WeatherType Good = new WeatherType("Good");
    public static readonly WeatherType Mid = new WeatherType("Mid");

    private static readonly WeatherType[] Values = { Bad, Good, Mid };

    public static WeatherType[] GetValues()
    {
        return (WeatherType[])Values.Clone();
    }

    private WeatherType(string name)
    {
        this.name = name;
    }
}

      



Now you have a static method to get a list of possible values, for example:

var values = WeatherType.GetValues();

      

0


source







All Articles