How to assign null to Generics (T)? The solution is Default(T)!

If you are working with generic methods / classes you may have the problem that you can not assign null to a generic type

which means that the following example results in the compile error (Can not convert expression type ‘null’ to return type ‘T’).

private T Foo<T>()
{
    return null;
}

The reason for this compile error is that T could even be a value type. And value types (int, double, etc.) can not be null.
Maybe you also tried a dirty workaround

private T Foo<T>()
{
    return (T)(object)null;
}

But this results in a NullPointer exception. Because it is more or less the same problem as before.
You assign null to a object and then to T which results in the same problem as before.

When i first faced the problem i was not sure how to solved it.
But Google telled me that there exists the default(T) keyword which solves this problem.

private T Foo<T>()
{
   return default(T);
}

I hope that it helps somebody which is in the same situation as I was 🙂

Advertisements
    • Konstantin
    • August 7th, 2010

    Yes, it has really helped!
    Many thanks!!!

  1. The double cast is evil! But necessary in AOP scenarios.

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: