views:

96

answers:

3

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...

+3  A: 

Who said it was wrong? Constants can be (and are) defined anywhere in a class hierarchy.

egrunin
Yes, I think it's pretty neat - but I haven't seen it done so I'm suspecting that there are some side effects...
antirysm
I think it's not about the constants but the nested classes.
Henk Holterman
Actually using Nested Classes For constants allows you to completely override or to extend them for sub-classes. There's added benefit to the concept.
Aren
+4  A: 

There is some guideline against public nested classes but I think this example falls inside the listed exception (ie: you're good).

Henk Holterman
Great to hear, any thoughts on why this use isn't more widespread - I can't be the only one who thought of it?
antirysm
Maybe you overestimate the use-cases. Constants are usually organized quite naturally alongside their classes. And classes shouldn't grow so big that their members need grouping.
Henk Holterman
Too many constants are definitely a potential sign of a bad design; however in my case we're talking about SharePoint which uses constants heavily.
antirysm
+2  A: 

Not saying that what you did is wrong, but what about using namespaces instead like this:

namespace 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";
    }
}
juharr
Yup, that would work when you have two levels - Category and Value but with nested classes you can add an infinite number of levels; ie Languages.English.American = "en-US".
antirysm
(Without adding additional namespaces I should add...)
antirysm
But why not add namespaces? In some situations that might be better, you can add to a ns in another file/assembly.
Henk Holterman
Yes, but the downside of using namespaces is that you can't have constants "on" them. Also with classes you could add properties that get default values/combine constants etc programmatically.
antirysm