Nesting Classes and Enums – Best Practices

object-orientedpatterns-and-practicesprogramming practicesstatic analysis

If an enum type is dedicate only to a specific class, does it make sense to declare it inside the class itself? I mean, would it help to understand that this enum type was designed to be used only with this class? Another option would be to put them inside the same namespace.

We also need to consider that another Dimension class could need a different enum type always called toleranceType.

Thanks.

public class Dimension
{
    public enum toleranceType
    {
        None,
        Symmetric,
        Deviation
    }

    public toleranceType ToleranceMode { get; set;}
}

Instead of:

public enum toleranceType
{
   None,
   Symmetric,
   Deviation
}

public class Dimension
{
    public toleranceType ToleranceMode { get; set;}
}

Best Answer

I don't think there is any compiled code difference between a nested enum and one in a namespace. You are just appending the container class or namespace to the full name.

However, Its usual to put classes in thier own files for readability.

Given that you don't get any functional difference, I would go with the convention of a new file for the enum, and just give it an appropriate namespace

If you have a pattern of many small classes each with its own specific enum, then I can see that nesting might be a neat solution though.

Related Topic