Can Interlocked.CompareExchange throw a 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
)
where T : class

and

NullReferenceException    The address of location1 is a null pointer.

But when I use the null reference for location1, I get no errors:

class A { }
class Program
{
    static void Main(string[] args)
    {
        A dest = null;
        A src = new A();
        // If dest is null, then replace with src.
        Interlocked.CompareExchange(ref dest, src, null);
    }
}

Can this be done? Is there a danger that in later versions of .NET this will throw NullReferenceException?

+4
source share
2 answers

As in the other answer, it is quite normal for your variable to contain null- this is about a reference to the variable null, and this cannot be in C # or most other managed languages ​​for this.

, Interlocked.CompareExchange a NullReferenceException, IL. , , :

  .method private hidebysig static void  Main(string[] args) cil managed
  {
    .entrypoint
    .maxstack  3
    .locals init ([0] int32& x)  // x is initialized to null
    ldloc.0
    ldc.i4.1
    ldc.i4.2
    call  int32 [mscorlib]System.Threading.Interlocked::CompareExchange(
      int32&, int32, int32)
    pop
    ret
  }

, NullReferenceException . Interlocked.CompareExchange, JIT lock cmpxchg.

@Sean, , NullReferenceException, ref out. , Int32.TryParse , NRE, " result is null", . , , .

+1

, location1 null, # . , , : "set location1 ( null) src, location1 null".

, location1 , #, ( ) , , throw a NullReferenceException.

, , Win32 api, / , null .

+4

All Articles