Search code examples
c#.netenumsprojects-and-solutionsclass-structure

Separate class for enums?


What is the general consensus towards a separate class in the business layer to store the definition of enums? Is this bad practice? Does this conform to good n-tier design? At the moment my enum definitions are dotted around different, what I would deem as, relevant classes - but I feel as though they should be in one place. Is this, in fact, a subjective question and relative to how I've structured the rest of the solution?


Solution

  • Keeping enums in separate class

    In this case you're tossing unrelated definitions into one class, for almost no benefits.

    Defining enum as nested type for class it relates to

    When you hold enums within a class, you may run into naming troubles:

    class Foo
    {
        public enum SomeType { /* ... */ }
        public SomeType SomeType { get; set; }
    }
    

    This would give an error that SomeType is already defined.

    It probably just boils to personal taste, but most often I put my enums along with the class that they are related to, without nesting them:

    public enum SomeType { } 
    public class Foo { }
    

    I was tempted many times to have them nested (we're talking about public enums of course), but the naming issues weren't worth it, for example:

    class Foo
    {
        public enum Enumeration { }
    }
    

    Then I can use such enum outside of Foo class, as: Foo.Enumeration, but following declaration (in same namespace):

    enum FooEnumeration { }
    class Foo { }
    

    gives similar result as you just don't have to type '.' when you are referencing enum: FooEnumeration. Moreover, the latter allows you for this:

    class Foo
    {
        public FooEnumeration Enumeration { get; set; }
    }
    

    which would cause aforementioned naming conflicts in previous case.

    Summary

    When using IDE with powerful GoTo capabilities, it seems to me that naming issues are far more important than 'physical' localization of the enum definition.