Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to apply InterLocked.Exchange for Enum Types in C#?

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?

like image 356
vinayvasyani Avatar asked Aug 24 '11 14:08

vinayvasyani


2 Answers

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).

like image 58
Steve Avatar answered Oct 18 '22 19:10

Steve


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;
like image 24
Corey Kosak Avatar answered Oct 18 '22 17:10

Corey Kosak