Question

Greetings,

I'm a beginner to OO and programming and I have the following situation:

I have a set of const values and enums that several of the classes I implement share.

These classes are independent i.e. other than sharing these values, they do not interact with each other, so inheriting them won't work.

I was wondering; If I create an empty class with just these consts and enums and then declare an object of these class in each class then i could use these values like:

globals.enum.enummember?

Is this sound programming or is there a better way of doing this?

Thanks for your time.

Was it helpful?

Solution

The best practice is to simply declare the enums alongside with your classes, not nested in a class. Actually, nested types are usually a bad idea, unless they are private. There are exceptions, of course, but for the most part you're better without nesting.

Constants have to be defined in a class, but you don't need to instantiate an object of the class to use them. Also they can be public, so you don't need to inherit anything. If you think about it hard enough, you should be able to figure out a good name for the class that contains these constants.

Practice shows that constants and enums rarely are simply global. Most of the time they are closely coupled with one or few classes. You should then define these constants as a part of the appropriate class and put enums in the same namespace as the class using them.

OTHER TIPS

You can use static class with static members to achieve desired behavior:

namespace A {
    public static class Enum1 {
       public static readonly int EnumMember1 = 1;
       public static readonly int EnumMember2 = 2;
       public static readonly int EnumMember3 = 3;
    }
}

You should use this in the following way:

int x = A.Enum1.EnumMember2;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top