C# – How to Handle ‘Possible Compare of Value Type with null’

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?

Best Answer

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.

Related Question