Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can Interlocked.CompareExchange throw NullReferenceException?

Tags:

c#

.net

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 a null reference for location1, I don't get any 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);
    }
}

Is it ok to do this? Is there a danger that this will throw NullReferenceException in later versions of .NET?

like image 503
Zantier Avatar asked Jun 09 '16 10:06

Zantier


1 Answers

The documentation is misleading here, as location1 cannot be null since in C# it must always reference an existing variable. So yes, it is ok as what you are saying is "set location1 (that currently contains null) to be src if location1 is already null".

In fact because location1 has to be a reference it is impossible to pass a null-reference in C#, although it it possible (and valid) to pass a reference to something that is null, and so this function will never throw a NullReferenceException.

I suspect this is down to the documentation being ported over from the Win32 api, where you have to pass a pointer to the location to read/write the variable, and it would be an error to pass null here.

like image 163
Sean Avatar answered Sep 27 '22 15:09

Sean