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.
-
5Why not use it directly?SLaks– SLaks2016年07月26日 20:58:44 +00:00Commented Jul 26, 2016 at 20:58
-
you don't even need to put the enums in a classSam I am says Reinstate Monica– Sam I am says Reinstate Monica2016年07月26日 21:05:59 +00:00Commented Jul 26, 2016 at 21:05
2 Answers 2
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.
2 Comments
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 }
}