Can't return 'null' from shared methods?

I have a general method, for example:

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

Which basically searches in db, and in some cases it does not return the result (and does not return), and I would like to return null.

However, this is obviously not possible due to "There is no implicit conversion between T and null." What should I do in this case?

+6
generics c #
source share
2 answers

T cannot be null, since T can be a value type. Try either returning the default value (T) or adding a class constraint to indicate that T can only be a reference type:

 public T GetLevelElement<T>(string name) where T : ILevelElement, class { [...] } 
+24
source share

Dustin Campbell is right. Another solution would be to return default(T) .

0
source share

All Articles