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.
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.
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)
{
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With