Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I return NULL from a generic method in C#?

Tags:

c#

generics

Two options:

  • Return default(T) which means you'll return null if T is a reference type (or a nullable value type), 0 for int, '\0' for char, etc. (Default values table (C# Reference))
  • Restrict T to be a reference type with the where T : class constraint and then return null as normal

return default(T);

You can just adjust your constraints:

where T : class

Then returning null is allowed.


Add the class constraint as the first constraint to your generic type.

static T FindThing<T>(IList collection, int id) where T : class, IThing, new()

  1. If you have object then need to typecast

    return (T)(object)(employee);
    
  2. if you need to return null.

    return default(T);