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

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...)

static T FindThing<T>(IList collection, int id) where T : IThing, new()
{
    foreach T thing in collecion
    {
        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?


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, '' for char etc
  • 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, IDisposable
    

    Then returning null is allowed.

    链接地址: http://www.djcxy.com/p/35360.html

    上一篇: 如何通过TCP连接到使用ADB的Android?

    下一篇: 我如何从C#中的泛型方法返回NULL?