Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Definition of enums outside the class body but inside namespace

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.

like image 440
surfasb Avatar asked Sep 19 '11 00:09

surfasb


2 Answers

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.

like image 195
Jordão Avatar answered Oct 24 '22 19:10

Jordão


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.

like image 44
Guffa Avatar answered Oct 24 '22 17:10

Guffa