HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpModerate

Function to toggle between two values of an enum

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
enumfunctiontwobetweenvaluestoggle

Problem

I have this code, but it looks a bit verbose:

enum MonitoringMode
{
    Seek,
    Destroy
}


void ToggleMonitoringMode()
{
    if (_monitoringMode == MonitoringMode.Seek)
        _monitoringMode = MonitoringMode.Destroy;
    else
    if (_monitoringMode == MonitoringMode.Destroy)
        _monitoringMode = MonitoringMode.Seek;
}


There are some well known idioms to toggle between two values, like:

bitwiseBoolean ^= bitwiseBoolean; // bit toggle
boolean = !boolean;               // boolean toggle
oneOrZero = 1 - oneOrZero;        // numeric toggle


Is there a similar, less verbose way to get the same result? I am not sure using the int value of enums would be safe or even "elegant" in C#.

Solution

Would there ever be a need to add more values to the MonitoringMode enum?

enum MonitoringMode
{
    Seek,
    Destroy,
    Something,
    SomethingElse
}


In that case, you're not "toggling" - you're mapping. And there's a data structure for that:

private static readonly IDictionary ModeMap = new Dictionary
{
    { MonitoringMode.Seek, MonitoringMode.Destroy },
    { MonitoringMode.Destroy, MonitoringMode.Seek },
    // ...
};


Then you could switch from one value to the next simply by using that map:

void ToggleMonitoringMode()
{
    _monitoringMode = ModeMap[_monitoringMode];
}


If there's not going to be a need to ever add more values, then I'd question the use of an enum type here, because you're really toggling between true and false states of some _isSeeking Boolean, which you already know how to toggle.

Code Snippets

enum MonitoringMode
{
    Seek,
    Destroy,
    Something,
    SomethingElse
}
private static readonly IDictionary ModeMap = new Dictionary<MonitoringMode,MonitoringMode>
{
    { MonitoringMode.Seek, MonitoringMode.Destroy },
    { MonitoringMode.Destroy, MonitoringMode.Seek },
    // ...
};
void ToggleMonitoringMode()
{
    _monitoringMode = ModeMap[_monitoringMode];
}

Context

StackExchange Code Review Q#101995, answer score: 12

Revisions (0)

No revisions yet.