Search code examples
c#class-designconstantsnested-class

Using nested classes for constants?


What's wrong with using nested classes to group constants?

Like so:

public static class Constants
{
    public static class CategoryA
    {
        public const string ValueX = "CatA_X";
        public const string ValueY = "CatA_Y";
    }
    public static class CategoryB
    {
        public const string ValueX = "CatB_X";
        public const string ValueY = "CatB_Y";
    }
}

Used like so:

Console.WriteLine(Constants.CategoryA.ValueY);
Console.WriteLine(Constants.CategoryB.ValueX);

You could also make the "Constants"-class partial...


Solution

  • There is some guideline (updated for fx 4.5) against public nested classes:

    √ DO use nested types when the relationship between the nested type and its outer type is such that member-accessibility semantics are desirable.

    X AVOID publicly exposed nested types. The only exception to this is if variables of the nested type need to be declared only in rare scenarios such as subclassing or other advanced customization scenarios.

    X DO NOT use nested types if the type is likely to be referenced outside of the containing type.

    I think your example matches the first point (ie: you're good).