MD Luffy
MD Luffy

Reputation: 556

c# check if a class has defined enum

I have a class like this

public class SomeClass {
public enum Status { A,B,C}
}

I want to do

bool enumExists = MysteryMethod("SomeClass.Status");

What goes inside MysteryMethod ?

Upvotes: 0

Views: 140

Answers (2)

Oguz Ozgul
Oguz Ozgul

Reputation: 7187

Enums are types themselves.

Nested types are named with + between the container class and the type name

Therefore, the name of the mystery method would be Type.GetType

public class SomeClass
{
    public enum Status
    {

    }
}

public class Program
{
    public static void Main(string[] args)
    {
        Type t = Type.GetType("Lab.SomeClass+Status", false);
        bool isEnum = t.IsEnum;
    }
}

Upvotes: 2

MD Luffy
MD Luffy

Reputation: 556

Figured it out:

var asm = System.Reflection.Assembly.GetExecutingAssembly(); 
var typ = asm.GetType("SomeClass+Status")
var enumExists = (typ != null && typ.IsEnum);

Trick is to put + after class name when you GetType.

Upvotes: 0

Related Questions