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, '\0' for char etc
  • Restrict T to be a reference type with the where T : class constraint and then return null as normal

Need Your Help

Opening a Word (.doc) Document from a stream

stream ms-word ms-office

I have a bunch of Word documents (.doc) stored in my SQL database that I need open, clean the properties such as Title, Subject etc and then save the file back to the database.

intrinsicContentSize vs. sizeThatFits. What's the difference? What are the use cases for each?

ios objective-c layout ios6 autolayout

I understand that intrinisicContentSize is part of the AutoLayout API, but other than that, I'm seeing lots of functionality overlap between it and the -sizeThatFits method.

What is an efficient way of deleting a large block of items from the start of a TList in Delphi

delphi delphi-2006 tlist

Delete (0) from a TList is expensive because all the subsequent items need to be moved down. If I need to delete a large number of items from the start of an even larger list what's the fastest way?

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.