-1

Is there a way how to return full enum by property? Here is example of what I want to do:

// MyEnums.cs
public enum Languages
{
    cs = 0,
    pl = 1,
    en = 2,
    de = 3,
}

// General.cs
public static MyEnums.Languages Languages
{
    get
    {
        return MyEnums.Languages;
    }
}
Cœur
  • 32,421
  • 21
  • 173
  • 232
Earlgray
  • 631
  • 7
  • 29
  • What? Why would you want to return a full enum? – Yytsi Nov 19 '15 at 14:08
  • 2
    `enum` is a *type*, it cannot be "returned". – Sergey Kalinichenko Nov 19 '15 at 14:08
  • 1
    No. I think you may be confused about what an enum is. It is a *type*, not simply a list. Trying to return `Languages` as a value makes about as much sense as `return System.String;`. Are you trying to return a `Languages` variable which has flags set for all languages? – Glorin Oakenfoot Nov 19 '15 at 14:09
  • I don't think that OP is asking the same thing as the duplicate. – Sergey Kalinichenko Nov 19 '15 at 14:13
  • Possible duplicate of [How do I enumerate an enum?](http://stackoverflow.com/questions/105372/how-do-i-enumerate-an-enum) – Patrick Hofman Nov 19 '15 at 14:18
  • Constructing a List or array full of the enum values should suffice. I don't understand why you would ever need to do this though. If it's for parsing just use a string with the desired enum name, and then use a switch statement to figure out which one it is. I've been programming for years and have never needed the "full" enum. – Krythic Nov 19 '15 at 15:11

3 Answers3

2

enum is a type, i guess you actually want to get all enum-values. You could use this wrapper:

public static class EnumWrapper<T> where T : struct
{
    public static T[] Values
    {
        get
        {
            Type ofT = typeof(T);
            if (!ofT.IsEnum) throw new ArgumentException("Must be enum type");
            return Enum.GetValues(ofT).Cast<T>().ToArray();
        }
    }
}

// ...

Languages[] languages = EnumWrapper<Languages>.Values;
Tim Schmelter
  • 411,418
  • 61
  • 614
  • 859
0

If you want to return all available values defined in the enum, you can use

Enum.GetValues(typeof(MyEnums.Languages));

and modify your method so it returns a MyEnums.Languages[] (or a List<MyEnums.Languages>, which is always easier to manage for calling code)

Gian Paolo
  • 3,802
  • 4
  • 13
  • 29
0

To get all values in the enum, use Enum.GetValues. You might also want to cast it back to the correct type:

Languages[] languages = Enum.GetValues(typeof(Languages)).Cast<Languages>().ToArray();
// languages is an array containing { Languages.cs, Languages.pl, Languages.en, Languages.de }
Kvam
  • 2,016
  • 1
  • 21
  • 29