System.Type.GetType

I am trying to reference enums by using a string with GetType(). I can’t seem to figure out why this doesn’t work when the class and enum are in a namespace. For example:

namespace MyNamespace
{
    public class MyClass
    {
        public enum MyEnum
        {
            Value1,
            Value2,
            Value3
        }
    }
}

My code:

string[] list = Enum.GetNames(Type.GetType("MyNamespace+MyClass+MyEnum"));

Without the namespace, this works fine. Is there a different way to get the namespace or something?

Delineate the names, class and enum with periods ( . ) not plus signs.

Basically the same way you’d write it in actual C#.

Why do you want to do this though? Why not just an array of enums?

1 Like

This is a C#/.net specific method independent of Unity specifically.

Refer to MSDN documentation for documentation pertaining to such things:

Here it’ll give you a break down of the delimiter uses for the string passed to this method.

Of course this is mostly useful if you’re reading in the string from somewhere (say you serilized the type). If you’re in C# you don’t need to parse the string you could just say it directly:

string[] list = Enum.GetNames(typeof(MyNamespace.MyClass.MyEnum));

or

string[] list = Enum.GetNames<MyNamespace.MyClass.MyEnum>();
3 Likes

Using periods doesn’t work. When simply doing, MyClass+MyEnum, the plus sign works. not the period. Idk.
I am doing this because I have a UI properties panel that needs to display properties for a wide variety of objects and referencing enums from components is one thing I need to do. Instead of adding enums to the code, one string variable in my scriptable objects can reference which enum is needed. I may resort to just doing an array of enums which the S.O. can reference just as easy, but I will need to add each enum to the array manually.

Thank you, the docs helped.

TopNamespace.SubNameSpace.ContainingClass+NestedClass,MyAssembly
1 Like

Right, actually yeah types nested in other types are delineated with a plus symbol. I always forget about that.

2 Likes