C# Refactoring – How to Deal with Almost the Same Enums

asp.netcenumrefactoring

I need to define enums in several classes. The majority of fields are the same in all of the enums. But one has one or two more fields, another has fewer fields. Now I wonder what is the best way to deal with this?

  1. Create separate enums

    public enum Foo {field1, field2, field5 };
    public enum Bar {field1, field2, field3, field4 };
    
  2. or use a general enum for them all

    public enum FooBar {field1, field2, field3, field4 , field5};
    

The enumerations contain the list of actions available for each class.

Update : sorry if the question was not clear enough . I want to use these enums as parameters in classes methods . for example classOne has a method as below :

public void DoSomeThing(Foo action,object moreData)
{
    // operation desired
}

here I want action to be limited to Insert , Update and Delete

while in classTwo :

public void DoSomeThingElse(Foo action)
{
    // operation desired
}

I want to limit action availabe to Insert and Select

Best Answer

You should use a different approach.

Create an enumeration which contains all available actions (insert, update, delete, etc.). So you can add a new (static) field to each class _ a list of items of that enumeration _ to represent the list of valid actions.

It makes no sense to have a separate enumeration for each class _ the enumerations semantically represent values of the same kind.

For example, you have an enumeration:

public enum ACTIONS { insert = 1, update = 2, delete = 3 }

In you class you would use it like this:

public class MyClass
{
    public static ACTIONS[] Actions = { ACTIONS.insert, ACTIONS.delete }; 
}
Related Topic