public enum MyEnum{Value1, Value2}
class MyClass
{
private MyEnum _field;
public MyEnum Field // added for convenience
{
get { return _field; }
set { Interlocked.Exchange(ref _field, value); // ERROR CS0452 }
}
}
could be solved with:
public enum MyEnum{Value1, Value2}
public class MyClass2
{
private int _field; //change to int
public MyEnum Field // added for convenience
{
get { return (MyEnum)_field; }
set { System.Threading.Interlocked.Exchange(ref _field, (int)value); }
}
}
Is there any better way for this problem?
Is there any better way for this problem?
If you need to use Interlocked.Exchange
then this is the best way, in fact I think it is the only way to Exchange an enum.
The reason you get the compiler error is that the compiler thinks you want to use Exchange<T>
, but T needs to be a reference type for this to work, since you are not using a reference type it fails. So, the best work around is to cast to an int
as you have done, and thus force the compiler to use the non-generic Exchange(int, int)
.
You appear to not need the "exchange" feature of Interlocked.Exchange, as you are ignoring its return value. Therefore I think the solution that might make you happiest is to mark _field as volatile:
private volatile MyEnum _field;
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