user3272018
user3272018

Reputation: 2429

Get class name of enum by its value

I have some enum

public enum MyEnum 
{ 
    Field1,
    Field2
}

and pass value in function

DoSmth(MyEnum.Field1);

How can i get classname "MyEnum" in that function

void DoSmth(Enum enumArg) 
{
    string className = Magic(enumArg); // className = "MyEnum"
}

Upvotes: 2

Views: 4914

Answers (2)

Brett Wolfington
Brett Wolfington

Reputation: 6627

Note that the code you've posted doesn't compile. enum is a reserved word and cannot be used as a variable name. The following will work, however.

void DoSmth(Enum e) 
{
    string className = e.GetType().Name; // className = "MyEnum"
}

Upvotes: 4

Andrey Korneyev
Andrey Korneyev

Reputation: 26896

If you just need to check if enum is MуEnum then it's better to check as if (enum is MyEnum)

If you need type name then you need enum.GetType().Name

Upvotes: 0

Related Questions