How to return NULL from a generic method?

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.

Comments

Popular posts from this blog

Auto Scroll in Common Controls

Convert typed library (.tlb) to .net assembly?

Disable close button on form - C#