591
votes

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?

13
Would nullable reference types (in C# 8) be the better solution to this now? docs.microsoft.com/en-us/dotnet/csharp/nullable-references Returning null regardless of whether T is Object or int or char.Alexander
Too bad that T? in the signature doesn't work. @Alexander-ReinstateMonica I've read the article but couldn't see a way to return null regardless of reference or value type.mireazma
@mireazma That's way too little information for me to be able to help. You should open a new question.Alexander

13 Answers

1035
votes

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
93
votes
return default(T);
38
votes

You can just adjust your constraints:

where T : class

Then returning null is allowed.

14
votes

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()
11
votes
  1. If you have object then need to typecast

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

    return default(T);
    
10
votes

Below are the two option you can use

return default(T);

or

where T : class, IThing
 return null;
7
votes

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.

5
votes

solution of TheSoftwareJedi works,

also you can archive it with using couple of value and nullable types:

static T? FindThing<T>(IList collection, int id) where T : struct, IThing
{
    foreach T thing in collecion
    {
        if (thing.Id == id)
            return thing;
    }
    return null;
}
4
votes

For completeness sake, it's good to know you could also do this:

return default;

It returns the same as return default(T);

2
votes

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 that it was a valid match if you go that route.

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

2
votes

Here's a working example for Nullable Enum return values:

public static TEnum? ParseOptional<TEnum>(this string value) where TEnum : struct
{
    return value == null ? (TEnum?)null : (TEnum) Enum.Parse(typeof(TEnum), value);
}
1
votes

Because of IThing is interface is not possible to use null. So you have to use default(T) to determine default value for actual type T which is defined before function is called.

using System;
using System.Collections.Generic;

public class Program
{
    public static void Main()
    {
        Console.WriteLine("Hello World");
        
        IThing x = new List<Thing>().FindThing(1);
        
    }

}

public static class Ext {
    public static T FindThing<T>(this IList<T> collection, int id) where T : IThing, new()
    {
        foreach (T thing in collection)
        {
            if (thing.Id == id) return (T)thing;
        }
    
        //return null; //not work
        //return (T)null; //not work
        //return null as T; //not work
        return default(T); //work
    }
}

public interface IThing { int Id {get; set;} }
public class Thing : IThing { public int Id {get;set;}}
0
votes

Another alternative to 2 answers presented above. If you change your return type to object, you can return null, while at the same time cast the non-null return.

static object FindThing<T>(IList collection, int id)
{
    foreach T thing in collecion
    {
        if (thing.Id == id)
            return (T) thing;
    }
    return null;  // allowed now
}