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?
-
Create separate enums
public enum Foo {field1, field2, field5 }; public enum Bar {field1, field2, field3, field4 };
-
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
4
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 };
}
4
The enumerations contain the list of actions available for each class.
Why are you trying to use enums
to solve your problem. I would create interface to cover all common behavior (actions) of my classes instead. You may create one ICommon
interface which will contain all your common behaviors for the class to support your design and class behaviors.
There are very good posts on this topic like Designing C# Software With Interfaces or you may also reference Wikipedia for common information – The concept of class interface.
1
Conceptually, are enums talking about the same concept or thing or are they just related? For example, I might have a Direction
enum and a Gears
enum. Both may have a Reverse
value but they mean very different things. In general, only merge concepts if they are the same. Otherwise you are making an assumption.
That said, from your comment above, it sounds like they are talking about the same concept (insert, update and delete) so I would merge them.
Also, if interop is a concern or they are similar, consider assigning the enum values fixed values, e.g. 1 for insert, 2 for delete and so on. It will make conversion and compatibility easier.
2