How can I return NULL from a generic method in C#?
return default(T);
Three options:
- Return
default
(ordefault(T)
for older versions of C#) which means you'll returnnull
ifT
is a reference type (or a nullable value type),0
forint
,'\0'
forchar
, etc. (Default values table (C# Reference)) - If you're happy to restrict
T
to be a reference type with thewhere T : class
constraint and then returnnull
as normal - If you're happy to restrict
T
to be a non-nullable value type with thewhere T : struct
constraint, then again you can returnnull
as normal from a method with a return value ofT?
- note that this is not returning a null reference, but the null value of the nullable value type.