Carven
Carven

Reputation: 15638

Getting the Enum without having to type its class name?

I notice that in C#, when I have an Enum, say:

class ClassObject {
   public static Enum EventType = {Click, Jump, Etc};
}

And when I have to access it, I have to go through it's main class and it is very verbose. For eg:

ClassObject.EventType.Click

I hope that I could access it in a shorter manner, say: EventType.Click, will allow me get that.

So what I thought I could try to create a separate class and extend it from Enum:

class EventType : Enum {
   Click, Jump, Etc;
}

However, this I'm getting a syntax error for this.

Actually, creating another separate class just for this purpose is a little troublesome and I don't even know if this is a good practice or not. But ideally, I just wish to shorten the name and probably avoid the need for having to type the class name before accessing the enum. Is this possible?

Upvotes: 4

Views: 2950

Answers (2)

hunter
hunter

Reputation: 63502

You can put the enum at the same depth of the class, it doesn't have to be a class member

namespace Test
{
    public enum EventType
    {
        Click,
        Jump,
        Etc
    };

    class ClassObject { }
}

Upvotes: 10

Adil
Adil

Reputation: 148110

You are defining the Enum in class scope. That is why you have to access it through class. Define it outside the class and access from every where you like. Nested Enum and classes are not directly accessible.

public static Enum EventType = {Click, Jump, Etc};

class ClassObject {

}

Upvotes: 4

Related Questions