I'm trying to use Interlocked.CompareExchange
with this enum:
public enum State {
Idle,
Running,
//...
}
The following code doesn't compile, but that's what I want do do:
if (Interlocked.CompareExchange(ref state, State.Running, State.Idle) != State.Idle) {
throw new InvalidOperationException("Unable to run - not idle");
}
Sure I can use a int instead of the enum and use a property:
private int state = (int)State.Idle;
public State { get { return (State)state; } }
Then cast the enums to a int:
if (Interlocked.CompareExchange(ref state, (int)State.Running, (int)State.Idle) != (int)State.Idle) {
throw new InvalidOperationException("Unable to run - not idle");
}
But are there better ways to do this?
To make it simple, no :-)
Sadly C#/.NET consider enum
s as full type, partially disconnected from their base type. Every time you try to do something "fancy" on an enum
you encounter some barrier.