dotnet thoughts 

a dotnet developer's technical blog

How to return null from a generic method

You can’t return a null from a generic method normally, if you try to return a null it will throw a compile time error. – Cannot convert null to type parameter ‘T’ because it could be a non-nullable value type. Consider using ‘default(T)’ instead.

public T GenericMethod<T>(object t)
{
    return null;
}

But you can resolve this error, by putting a class constraint.

public T GenericMethod<T>(object t) where T : class
{
    return null;
}

No Responses to “How to return null from a generic method”

RSS feed for comments on this post. TrackBack URL

Leave a Response

*