tags:

views:

3803

answers:

6

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?

+1  A: 
return default(T);
Ricardo Villamil
This link:http://msdn.microsoft.com/en-us/library/xwth0h0d(VS.80).aspx should explain why.
Harper Shelby
Damn it, I would've saved a lot of time had I known about this keyword - thanks Ricardo!
Paul Betts
A: 

Take the recommendation of the error....and either user default(T) or new T.

You will have to add in a comparison in your code to ensure htat it was a valid match if you go that route.

Otherwise, potentially consider an output parameter for "match found".

Mitchel Sellers
+38  A: 

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
Jon Skeet
+2  A: 

Your other option would be to to add this to the end of your declaration:

    where T : class
    where T: IList

That way it will allow you to return null.

BFree
+3  A: 

You can just adjust your constraints:

where T : class, IDisposable

Then returning null is allowed.

TheSoftwareJedi
Thanks. I cannot choose 2 answers as the accepted solution, so I choose John Skeet's cause his answer has two solutions.
edosoft
+2  A: 

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()
Min
Thanks. I cannot choose 2 answers as the accepted solution, so I choose John Skeet's cause his answer has two solutions.
edosoft