Jul 27, 2012

How to return NULL from a generic method?

1 comment
Generally we can’t return a null from a generic method, 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, we can resolve this error by adding a Class constraint as follows,

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

For every thing there could be a hack :)

If you feel this is helpful or you like it, Please share this using share buttons available on page.

1 comment :