Definition of enums outside the class body but inside namespace

21,287

Solution 1

Enums are types, just like classes. When you declare an enum inside a class, it's just a nested type. A nested enum just hides other enums with the same name that are declared in outer scopes, but you can still refer to the hidden enum through its fully qualified name (using the namespace prefix, in your example).

The decision whether to declare a top level enum or a nested enum depends on your design and whether those enums will be used by anything other than the class. You can also make a nested enum private or protected to its enclosing type. But, top level enums are far more common.

Solution 2

If you put the enumerations in the class, you would need to specify the class name every time you use it outside of the class, for example:

SomeLongClassName x = new SomeLongClassName(SomeLongClassName.Game.High, SomeLongClassName.Switch.On);

instead of:

SomeLongClassName x = new SomeLongClassName(Game.High, Switch.On);

You could decide to put the ennumeration inside a class if it's used only by that class, but that kind of isolation only works for classes. If you have an enumeration that is only used by a single method, you can't put it inside the method.

Share:
21,287
surfasb
Author by

surfasb

For those who ask about my Avy. http://www.youtube.com/watch?v=ECG6ObpLoXY&feature=related Super User Blog. http://blog.superuser.com/

Updated on July 22, 2022

Comments

  • surfasb
    surfasb almost 2 years

    Today, I ran into some code that goes like this.

    namespace Foo
    {
    
        public enum Game{ High, Low};
        public enum Switch{On, Off};
    
        public class Bar()
        {
        // Blah
        }
    }
    

    I could not figure out what the difference between that and declaring the enums inside the class was. AFAIK, you can still "override" those enums inside the class.

  • surfasb
    surfasb over 12 years
    So the proper name is a top level enum?
  • Jordão
    Jordão over 12 years
    I think so... You can find these definition here.