Carmax
Carmax

Reputation: 2917

How do I get an enum type as string from one of it's values?

I'm sure this is simple, but I just can't figure it out.

I would like to return the type name of an enum by passing in one of its members.

All my searches show how to get member names from int values, or display names from string values, etc, etc. But I can't find anything that will show me how this is done.

string name1 = GetEnumName(Colour.Black)
// should be "Colour"


string name2 = GetEnumName(Flower.Daisy)
//should be "Flower"


public static string GetEnumName(Enum myEnum)
{
    // ...what goes here...?
}    

public enum Colour 
{
     Black, White, Pink, Blue
}
public enum Flower
{
    Pansy, Daffodil, Daisy
}

Upvotes: 2

Views: 227

Answers (1)

Farhad Jabiyev
Farhad Jabiyev

Reputation: 26635

You can use .GetType().Name.

GetType() gets the Type of the current instance. And it has the Name property. Keep in mind that, you can also use .GetType().ToString() or .GetType().FullName which will return namespace+name of the type of the object.

Also don't forget that you can use is keyword to find out if the object is the specified type or not. F.e:

if(myEnum is Flower)

Upvotes: 5

Related Questions