0

I currently have a generic method where I want to do some validation on the parameters before working on them. Specifically, if the instance of the type parameter T is a reference type, I want to check to see if it's null and throw an ArgumentNullException if it's null.

Something along the lines of:

// This can be a method on a generic class, it does not matter.
public void DoSomething<T>(T instance)
{
    if (instance == null) throw new ArgumentNullException("instance");

Note, I do not wish to constrain my type parameter using the class constraint.

I thought I could use Marc Gravell's answer on "How do I compare a generic type to its default value?", and use the EqualityComparer<T> class like so:

static void DoSomething<T>(T instance)
{
    if (EqualityComparer<T>.Default.Equals(instance, null))
        throw new ArgumentNullException("instance");

But it gives a very ambiguous error on the call to Equals:

Member 'object.Equals(object, object)' cannot be accessed with an instance reference; qualify it with a type name instead

How can I check an instance of T against null when T is not constrained on being a value or reference type?

Community
  • 1
  • 1
casperOne
  • 73,706
  • 19
  • 184
  • 253
  • 2
    It's been a while since the question was asked, but I'm curious: what's wrong with `instance == null`? According to Eric Lippert's [answer](http://stackoverflow.com/questions/8823239/comparing-a-generic-against-null-that-could-be-a-value-or-reference-type/8824259#8824259) the comparison will simply be replaced with `false` for value types. Is there some other scenario where this does not suffice? – enzi Mar 18 '15 at 09:08
  • @enzi I believe that you get a compiler warning (which would be an error if you treat errors as warnings) if it's a struct type (or not constrained appropriately). – casperOne Oct 20 '15 at 16:28
  • I don't get a warning for a null check on a type parameter that is not constrained. – enzi Oct 21 '15 at 10:25
  • @enzi In the case that you can't constrain it to class but want to make sure you're working with a value and not get a `NullReferenceException`. Think auto generating code from any type (structures or class) and not wanting to change your method name because signatures do not use constraints to determine difference. – casperOne Oct 21 '15 at 11:25
  • 1
    you can just check with `instance == null`, you don't need constraints or a cast to `object`, it just works for class and struct types. I don't get why the question was asked in the first place, merely curious if there can be cases where a simple `== null` _doesn't_ work. As far as I know, it just works and all the complicated solutions here are pointless. – enzi Oct 21 '15 at 15:48
  • 1
    I know this question is quite old, but I agree with @enzi. According to [this Eric Lippert answer](https://stackoverflow.com/questions/8823239/comparing-a-generic-against-null-that-could-be-a-value-or-reference-type) and [this Jon Skeet answer](https://stackoverflow.com/questions/5340817/what-should-i-do-about-possible-compare-of-value-type-with-null?noredirect=1&lq=1) simply check `instance == null` works. According to Jon Skeet answer, any compiler warning can safely be ignored. – Enrico Massone Jun 10 '21 at 07:57
  • 1
    Well, since it is the future now, there is a new way to answer this: `instance is null`. As the [Microsoft docs](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/proposals/csharp-8.0/patterns#constant-pattern) themselves say: _We expect to see `e is null` as the most common way to test for null in newly written code, as it cannot invoke a user-defined `operator==`._ – enzi Jun 12 '21 at 15:11
  • @enzi This is indeed the answer now. – casperOne Jun 12 '21 at 21:21

1 Answers1

7

There's a few ways to do this. Often, in the framework (if you look at source code through Reflector), you'll see a cast of the instance of the type parameter to object and then checking that against null, like so:

if (((object) instance) == null)
    throw new ArgumentNullException("instance");

And for the most part, this is fine. However, there's a problem.

Consider the five main cases where an unconstrained instance of T could be checked against null:

  • An instance of a value type that is not Nullable<T>
  • An instance of a value type that is Nullable<T> but is not null
  • An instance of a value type that is Nullable<T> but is null
  • An instance of a reference type that is not null
  • An instance of a reference type that is null

In most of these cases, the performance is fine, but in the cases where you are comparing against Nullable<T>, there's a severe performance hit, more than an order of magnitude in one case and at least five times as much in the other case.

First, let's define the method:

static bool IsNullCast<T>(T instance)
{
    return ((object) instance == null);
}

As well as the test harness method:

private const int Iterations = 100000000;

static void Test(Action a)
{
    // Start the stopwatch.
    Stopwatch s = Stopwatch.StartNew();

    // Loop
    for (int i = 0; i < Iterations; ++i)
    {
        // Perform the action.
        a();
    }

    // Write the time.
    Console.WriteLine("Time: {0} ms", s.ElapsedMilliseconds);

    // Collect garbage to not interfere with other tests.
    GC.Collect();
}

Something should be said about the fact that it takes ten million iterations to point this out.

There's definitely an argument that it doesn't matter, and normally, I'd agree. However, I found this over the course of iterating over a very large set of data in a tight loop (building decision trees for tens of thousands of items with hundreds of attributes each) and it was a definite factor.

That said, here are the tests against the casting method:

Console.WriteLine("Value type");
Test(() => IsNullCast(1));
Console.WriteLine();

Console.WriteLine("Non-null nullable value type");
Test(() => IsNullCast((int?)1));
Console.WriteLine();

Console.WriteLine("Null nullable value type");
Test(() => IsNullCast((int?)null));
Console.WriteLine();

// The object.
var o = new object();

Console.WriteLine("Not null reference type.");
Test(() => IsNullCast(o));
Console.WriteLine();

// Set to null.
o = null;

Console.WriteLine("Not null reference type.");
Test(() => IsNullCast<object>(null));
Console.WriteLine();

This outputs:

Value type
Time: 1171 ms

Non-null nullable value type
Time: 18779 ms

Null nullable value type
Time: 9757 ms

Not null reference type.
Time: 812 ms

Null reference type.
Time: 849 ms

Note in the case of a non-null Nullable<T> as well as a null Nullable<T>; the first is over fifteen times slower than checking against a value type that is not Nullable<T> while the second is at least eight times as slow.

The reason for this is boxing. For every instance of Nullable<T> that is passed in, when casting to object for a comparison, the value type has to be boxed, which means an allocation on the heap, etc.

This can be improved upon, however, by compiling code on the fly. A helper class can be defined which will provide the implementation of a call to IsNull, assigned on the fly when the type is created, like so:

static class IsNullHelper<T>
{
    private static Predicate<T> CreatePredicate()
    {
        // If the default is not null, then
        // set to false.
        if (((object) default(T)) != null) return t => false;

        // Create the expression that checks and return.
        ParameterExpression p = Expression.Parameter(typeof (T), "t");

        // Compare to null.
        BinaryExpression equals = Expression.Equal(p, 
            Expression.Constant(null, typeof(T)));

        // Create the lambda and return.
        return Expression.Lambda<Predicate<T>>(equals, p).Compile();
    }

    internal static readonly Predicate<T> IsNull = CreatePredicate();
}

A few things to note:

  • We're actually using the same trick of casting the instance of the result of default(T) to object in order to see if the type can have null assigned to it. It's ok to do here, because it's only being called once per type that this is being called for.
  • If the default value for T is not null, then it's assumed null cannot be assigned to an instance of T. In this case, there's no reason to actually generate a lambda using the Expression class, as the condition is always false.
  • If the type can have null assigned to it, then it's easy enough to create a lambda expression which compares against null and then compile it on-the-fly.

Now, running this test:

Console.WriteLine("Value type");
Test(() => IsNullHelper<int>.IsNull(1));
Console.WriteLine();

Console.WriteLine("Non-null nullable value type");
Test(() => IsNullHelper<int?>.IsNull(1));
Console.WriteLine();

Console.WriteLine("Null nullable value type");
Test(() => IsNullHelper<int?>.IsNull(null));
Console.WriteLine();

// The object.
var o = new object();

Console.WriteLine("Not null reference type.");
Test(() => IsNullHelper<object>.IsNull(o));
Console.WriteLine();

Console.WriteLine("Null reference type.");
Test(() => IsNullHelper<object>.IsNull(null));
Console.WriteLine();

The output is:

Value type
Time: 959 ms

Non-null nullable value type
Time: 1365 ms

Null nullable value type
Time: 788 ms

Not null reference type.
Time: 604 ms

Null reference type.
Time: 646 ms

These numbers are much better in the two cases above, and overall better (although negligible) in the others. There's no boxing, and the Nullable<T> is copied onto the stack, which is a much faster operation than creating a new object on the heap (which the prior test was doing).

One could go further and use Reflection Emit to generate an interface implementation on the fly, but I've found the results to be negligible, if not worse than using a compiled lambda. The code is also more difficult to maintain, as you have to create new builders for the type, as well as possibly an assembly and module.

casperOne
  • 73,706
  • 19
  • 184
  • 253
  • +1 Consider changing the `if (((object) default(T)) != null) return t => false` check with `if (typeof(T).IsClass || typeof(T).IsInterface || (typeof(T).IsGenericType && typeof(T).GetGenericTypeDefinition() == typeof(Nullable<>))) return t => false`. I think this would be a more explicit way of detecting nullability. – Sergey Kalinichenko Dec 21 '12 at 16:38
  • @dasblinkenlight Perhaps more explicit, but not very succinct? What are the advantages of expanding it to that? You can also check if it's a value type that is nullable or not a value type (that might make it shorter). – casperOne Dec 21 '12 at 17:33
  • While understanding the `((object) default(T)) != null` expression requires some amount of thinking, my alternative reads almost like "plain English": "If type of `T` is a class, an interface, or a generic type based on `Nullable<>`..." spells out the exact condition very explicitly. To me, the less thinking is required to understand a piece of code, the better :) – Sergey Kalinichenko Dec 21 '12 at 17:43
  • @dasblinkenlight I see where you're coming from. I want to do some research to see that *all* the cases are covered. However, given that this is what's in the codebase for WPF, I think it's safe to assume that the casting to object check does cover all bases; you have to be *correct* before you're *concise*. – casperOne Dec 21 '12 at 18:11