c# - Can Interlocked.CompareExchange throw NullReferenceException? -
from https://msdn.microsoft.com/en-us/library/bb297966(v=vs.110).aspx
[comvisibleattribute(false)] public static t compareexchange<t>( ref t location1, t value, t comparand ) t : class
and
nullreferenceexception address of location1 null pointer.
but when use null reference location1
, don't errors:
class { } class program { static void main(string[] args) { dest = null; src = new a(); // if dest null, replace src. interlocked.compareexchange(ref dest, src, null); } }
is ok this? there danger throw nullreferenceexception
in later versions of .net?
as other answer says, it's ok have variable contain null
-- it's reference variable being null
, , can't happen in c#, or other managed languages matter.
that said, can make interlocked.compareexchange
throw nullreferenceexception
working directly il. there have tricky if want remain in realm of managed, verifiable code:
.method private hidebysig static void main(string[] args) cil managed { .entrypoint .maxstack 3 .locals init ([0] int32& x) // x initialized null ldloc.0 ldc.i4.1 ldc.i4.2 call int32 [mscorlib]system.threading.interlocked::compareexchange( int32&, int32, int32) pop ret }
this code pass verification, throw nullreferenceexception
@ runtime. stack trace not show interlocked.compareexchange
, since jit compiler inlines single lock cmpxchg
instruction.
as @sean correctly pointed out, should not justify documentation saying method may throw nullreferenceexception
, because technique can used break function taking ref
or out
parameter. example, int32.tryparse
not document can throw nre if "the address of result
null
", nor expect to. managed code implicitly expected well-behaved when comes references.
Comments
Post a Comment