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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With