Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get type of enum in .NET class

Consider the following C# class declaration:

public class MyClass {
    private enum Colours { Red, Green, Blue }
}

Which is sat in a separate class library/DLL.

Given just the typeof(MyClass) object (System.Type), is there any way to check if the class contains an enum called Colours at runtime and if so return it's corresponding System.Type object?

What I'm trying to do is write some generic code that's given the type of a class and determine if contains a specifically named enum inside and then query the values in the enum.

I know how to use Reflection to query things like GetFields, GetProperties etc. but there isn't a GetClasses or GetEnums method in System.Type.

I suspect this kind of information is in the assembly?

like image 508
Rob Nicholson Avatar asked Dec 15 '22 11:12

Rob Nicholson


1 Answers

Just do:

var res = typeof(MyClass).GetNestedType("Colours", BindingFlags.NonPublic);

Test res != null to see if such type exists.

Then test res.IsEnum to see if the nested type is an enum.

Addition: If the nested type is occasionally nested public, use BindingFlags.NonPublic | BindingFlags.Public instead.

like image 199
Jeppe Stig Nielsen Avatar answered Dec 17 '22 02:12

Jeppe Stig Nielsen