Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enum subset or subgroup in C#

Tags:

c#

enums

I have an existing enum with numerous items in it.

I also have existing code which does certain things with this enum.

I would now like a way to view only a subset enum members. What I'm looking for is a way to divide my enum into groups. I need to preserve the (int) value of each member and I need to preserve the ability to view all enum members if needed.

The only thing I can think of is to just create a new enum for each subenum that only contain the items I want using the same name and value.

This works but violates the whole no repetition principle.

I don't expect anyone to have a better alternative but I thought I'd ask just in case someone had a fancy trick to show me.

Thanks, as always.

like image 373
srmark Avatar asked Feb 05 '09 23:02

srmark


2 Answers

I would go with this (which works in VB.NET at least)

enum MySuperEnumGroup  {    Group1Item1,    Group1Item2,    Group1Item3,     Group2Item1,    Group2Item2,    Group2Item3,     Group3Item1,    Group3Item2,    Group3Item3,  }   enum MySubEnumGroup  { Group2Item1 = MySuperEnumGroup.Group2Item1  Group3Item1 = MySuperEnumGroup.Group3Item1  Group3Item3 = MySuperEnumGroup.Group3Item3 } 

Then do some kind of CType when you need to.

like image 101
ed_hubbell Avatar answered Oct 19 '22 21:10

ed_hubbell


You could define the values using an enumeration but then reference them via constants in static classes so that your developers don't get over-faced by the large enum. You could have:

enum MySuperEnumGroup {   Group1Item1,   Group1Item2,   Group1Item3,    Group2Item1,   Group2Item2,   Group2Item3,    Group3Item1,   Group3Item2,   Group3Item3, }  static class MySuperEnumGroup_Group1 {   public const MySuperEnumGroup Item1 = MySuperEnumGroup.Group1Item1;   public const MySuperEnumGroup Item2 = MySuperEnumGroup.Group1Item2;   public const MySuperEnumGroup Item3 = MySuperEnumGroup.Group1Item3; }  static class MySuperEnumGroup_Group2 {   public const MySuperEnumGroup Item1 = MySuperEnumGroup.Group2Item1;   public const MySuperEnumGroup Item2 = MySuperEnumGroup.Group2Item2;   public const MySuperEnumGroup Item3 = MySuperEnumGroup.Group2Item3; }  //etc. 
like image 30
Jeff Yates Avatar answered Oct 19 '22 21:10

Jeff Yates