Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What should I do about "Possible compare of value type with 'null'"?

Tags:

c#

While writing this method for a custom NUnit Constraint.

    private void AddMatchFailure<TExpected, TActual>(string failureName, TExpected expected, TActual actual)
    {
        _matchFailures.Add(
            String.Format(MatchFailureFormat, failureName,
            (expected == null) ? "null" : expected.ToString(),
            (actual == null) ? "null" : actual.ToString()));
    }

Resharper warns that expected and actual might be ValueType objects.

e.g. TExpected is DateTime
   expected == null;//  but DateTime is a struct.

What are the rules when comparing a ValueType to null and how should I write the method to account for that without limiting the generic parameters by adding a class constraint?

like image 909
Grokodile Avatar asked Mar 17 '11 14:03

Grokodile


3 Answers

Don't change the code - just ignore the warning. If the type parameter is a non-nullable value type, the comparison will always fail and it'll always call ToString() instead. I don't know whether it's actually JITted away, but I wouldn't be surprised... and this doesn't sound like it's performance-critical code anyway :)

I'd personally leave the warning "on", but ignore it in this particular case - possibly with a comment.

I think I came across the same warning a few times when reimplementing LINQ to Objects.

like image 160
Jon Skeet Avatar answered Oct 18 '22 22:10

Jon Skeet


What are the rules when comparing a ValueType to null and how should I write the method to account for that without limiting the generic parameters by adding a class constraint?

If you do not know that they will be reference types, then you can say

private void AddMatchFailure<TExpected, TActual>(
    string failureName,
    TExpected expected,
    TActual actual
) {
    _matchFailures.Add(
        String.Format(MatchFailureFormat, failureName,
        IsDefault<TExpected>(expected) ? DefaultStringForType<TExpected>() : expected.ToString(),
        IsDefault<TActual>(actual) ? DefaultStringForType<TActual>() : actual.ToString()
    );
}

private bool IsDefault<T>(T value) {
    if(typeof(T).IsValueType) {
        return default(T).Equals(value);
    }
    else {
        return Object.Equals(null, value);
    }
}

private string DefaultStringForType<T>() {
    if(typeof(T).IsValueType) {
        return default(T).ToString();
    }
    else {
        return "null";
    }
}
like image 31
jason Avatar answered Oct 19 '22 00:10

jason


I'm using something like this to check for null on generic types:

if (Equals(result, Default(T)))
like image 2
Billy Avatar answered Oct 19 '22 00:10

Billy