lionheartdamacy
lionheartdamacy

Reputation: 1

Setting an enum as another enum within a C# class

I'm currently working on a C# program that utilizes a fair number of enums. It's organized in such a way that a class contains many enums, and there are several of these classes. However, a couple enums are identical between the two--for organizational purposes, it would be nice to have a kind of 'SharedEnums' class, and then do something like this:

public class FirstEnumCollection {
    public enum Fruits = SharedEnums.Fruits;
    //insert non-shared enums here
}

public class FirstEnumCollection {
    public enum Fruits = SharedEnums.Fruits;
    //insert non-shared enums here
}

public class SharedEnums { 
    public enum Fruits {
        Apple,
        Pear
    }
}

This way, we won't have the same enums declared multiple times across classes, and changing the shared enum will change the enum in both classes. I've tried several variations of my example without luck, and I'm fairly certain it can't be done, but would like confirmation.

Upvotes: 0

Views: 1343

Answers (2)

Igor Damiani
Igor Damiani

Reputation: 1927

An enum can be defined at namespace scope, you are not required to create an enum inside a class. You can imagine an enum like a struct, or a class, it's a type that you can use in the code. So, define it at namespace scope

namespace MyCode
{
    public enum Days { M, T, W, T, F, Sa, Su }
}

Upvotes: 1

Scott Hannen
Scott Hannen

Reputation: 29222

An enum doesn't need to "belong" to a class. You can declare it outside of any class:

public enum Fruits {
    Apple,
    Pear
}

and then use it within any class.

Upvotes: 5

Related Questions