Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot return 'null' from generic methods?

Tags:

c#

.net

generics

I have a generic method like:

public T GetLevelElement<T>(string name) where T : ILevelElement
{
    //[...]
}

Which basically performs a lookup in a db and in some cases it does not (and cannot return) a result and I would like to return null.

However that's obviously not possible because of 'There is no implicit conversion between T and null'. What should I do in this case?

like image 741
Jörg Battermann Avatar asked Aug 05 '09 14:08

Jörg Battermann


People also ask

How do I return a generic null?

So, to return a null or default value from a generic method we can make use default(). default(T) will return the default object of the type which is provided.

Can you have a generic method in a non generic class C#?

In C# and similar languages, all methods belong to classes. Some of these classes are generic, some are just simple, ordinary classes. We can have generic methods in both generic types, and in non-generic types.


1 Answers

T cannot be null, because T could be a value type. Try returning default(T) or adding a class constraint to indicate that T can only be a reference type like so:

public T GetLevelElement<T>(string name) where T : ILevelElement, class
{
    [...]
}
like image 188
Dustin Campbell Avatar answered Sep 25 '22 14:09

Dustin Campbell