Why does R# give me a "Possible compare of value type with null" for this code?

While developing I wrote a method like this:

public void Test<T>(T data)
{
    if (!typeof(T).IsValueType && data == null)
    {
        // stuff here
    }
}
             

Very simplified of course but this piece of code still gets R# to generate a "Possible compare of value type with null" at the "== null" part.
Why is that? Obviously "data" will no longer be a ValueType is it passes the "!typeof(T).IsValueType" part.

5 comments
Comment actions Permalink

I agree however you can avoid the warning with

public void Test<T>(T data)
{
    if (!typeof(T).IsValueType && data == default(T))
    {
        // stuff here
    }
}


         

0
Comment actions Permalink

That changes the meaning of the code.

For example, if T is int and data is 0, "0 == null" will be false, but "0 == default(int)" will be true.

0
Comment actions Permalink

But if T is int then typeof(T).IsValueType wil be true.....

Alternatively you could use:

.public void Test<T>(T data)

{
    if (!typeof(T).IsValueType && object.ReferenceEquals(data, null))
    {
        // stuff here
    }
}
0
Comment actions Permalink

Of course; I obviously need more coffee! :8}

However, you can't use the equality operator on a generic type unless one operand is the literal "null". You'll get the compiler error "Operator '==' cannot be applied to operands of type 'T' and 'T'".

0
Comment actions Permalink

"Possible compare of value type with null" warning in this case just warns user that he possibly has missed a case where generic type can beof a  value type. In the provided code ReSharper could infere that "data" is definitely not of a value type but currently it does not have this type of analysis (I've created feature request for it: https://youtrack.jetbrains.com/issue/RSRP-432179)

While this is not implemented, I can suggest to disable the warning either in options or by a comment (hit "Alt+Enter" when the cursor is on the underlinded text and select the option)

0

Please sign in to leave a comment.