Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Interlocked.Exchange nullable decimal

I want to exchange two nullable decimal values, like this:

o2 = Interlocked.Exchange(ref o1, o2);

The type 'decimal?' must be a reference type in order to use it as parameter 'T' in the generic type or method 'System.Threading.Interlocked.Exchange(ref T, T)'.

Is there better idea than this:

decimal? temp = o1;
o1 = o2;
o2 = temp;

Thanks in advance!

like image 463
Pingpong Avatar asked Feb 12 '26 06:02

Pingpong


1 Answers

Two thoughts:

  • treat it as object and cast at the consumer
  • create a Box<T> class where T:struct (and make it immutable), and swap some Box<decimal> references

In both cases, the consumer should take a clone of the value before anything else (no double reads; it may change between reads).

like image 72
Marc Gravell Avatar answered Feb 14 '26 21:02

Marc Gravell



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!