snippetcsharpCritical
How can I return NULL from a generic method in C#?
Viewed 0 times
howfromreturnmethodcangenericnull
Problem
I have a generic method with this (dummy) code (yes I'm aware IList has predicates, but my code is not using IList but some other collection, anyway this is irrelevant for the question...)
This gives me a build error
"Cannot convert null to type parameter
'T' because it could be a value type.
Consider using 'default(T)' instead."
Can I avoid this error?
static T FindThing(IList collection, int id) where T : IThing, new()
{
foreach (T thing in collection)
{
if (thing.Id == id)
return thing;
}
return null; // ERROR: Cannot convert null to type parameter 'T' because it could be a value type. Consider using 'default(T)' instead.
}
This gives me a build error
"Cannot convert null to type parameter
'T' because it could be a value type.
Consider using 'default(T)' instead."
Can I avoid this error?
Solution
Three options:
- Return
default(ordefault(T)for older versions of C#) which means you'll returnnullifTis a reference type (or a nullable value type),0forint,'\0'forchar, etc. (Default values table (C# Reference))
- If you're happy to restrict
Tto be a reference type with thewhere T : classconstraint and then returnnullas normal
- If you're happy to restrict
Tto be a non-nullable value type with thewhere T : structconstraint, then again you can returnnullas 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.
Context
Stack Overflow Q#302096, score: 1170
Revisions (0)
No revisions yet.