Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using an enum value to represent two enum values

Tags:

c#

.net

enums

Picture the scene.

public enum SaveStates
{
    Saved,               //Represents a successful save.
    SavedWithChanges,    //Represents a successful save, where records were modified
    SavedWithoutChanges  //Represents a successful save, but no records were modified
}

In this scenario, the enumeration can be considered Saved if it's SavedWithChanges or SavedWithoutChanges.

So if I were to have a variable like this:

SaveStates lastState = SaveStates.SavedWithoutChanges;

I'd ideally like to do something like this:

if (lastState == SaveStates.Saved)
{
    //The state is saved, do something awesome.
}

I can of course do this:

if (lastState == SaveStates.SavedWithChanges || lastState == SaveStates.SavedWithoutChanges)
{
    ...

However this is a bit tedious and I can't assume that another developer is going to understand how to correctly use the enumeration.

Each enumeration is required as there may be an instance where we might want to do something specific in the event of a save where there has been no changes for example.

I'm open to alternative design ideas.

like image 485
Mike Eason Avatar asked Dec 14 '22 11:12

Mike Eason


2 Answers

If what worries you is code readability, you can use a little extension method like this:

public static class SaveStatesExtension
{
    public static bool IsSavedState(this SaveStates state) {
        return state == SaveStates.SavedWithChanges || 
               state == SaveStates.SavedWithoutChanges;
    }
}

Then your usage example becomes:

if (lastState.IsSavedState())
{
    //The state is saved, do something awesome.
}

Of course the Saved member in the enum is no longer needed in this case.

like image 69
Konamiman Avatar answered Dec 17 '22 01:12

Konamiman


If you're going to do it with a Flags enum, you should make it self-documenting

[Flags]
public enum SaveStates
{
    Saved = 1,
    WithChanges = 2,
    SavedWithoutChanges = Saved, // a bit pointless! Its the same as Saved
    SavedWithChanges = Saved | WithChanges  // has value "3"
}

And then, as per other answers

if ((lastState & SaveStates.Saved) == SaveStates.Saved)
{

}
like image 32
Jamiec Avatar answered Dec 17 '22 02:12

Jamiec