C# – Cannot convert null to type parameter ‘T’ because it could be a non-nullable value type

Problem

You’re trying to return null from a generic method and you’re getting the following compiler error:

Cannot convert null to type parameter ‘T’ because it could be a non-nullable value type. Consider using ‘default(T)’ instead

You can’t return null because the compiler doesn’t know if T is nullable.

Solution

There are a few options for solving this depending your scenario.

Let’s say your generic method looks like the method below, and then let’s look at the options for solving this error.

public T Load<T>() { return null; }

Option 1 – return default(T)

Return default(T) instead of null.

public T Load<T>() { return default(T); }

This is the option suggested by the compiler error itself. Use this if you are allowing any type to be used.

If T is nullable, it’ll return null. Otherwise it’ll return the default for the specified type. For example, if you call this with Load<int>() it’ll return 0.

Option 2 – constrain T to a nullable type

Return null and constrain T to class.

public T Load<T>() where T : class { return null; }

Use this option if you know you’re going to using this generic method with reference types – such as classes/interfaces.

For example, let’s say you’re loading multiple interfaces, like this:

var dataReceiverPlugin = typeLoader.Load<IDataReceiverPlugin>(); var dataSenderPlugin = typeLoader.Load<IDataSenderPlugin>(); public interface IDataReceiverPlugin { } public interface IDataSenderPlugin { }

Option 3 – constrain T to a specific class

Return null and constrain T to a specific class.

public T Load<T>() where T : PluginBase { return null; }

For example, you’d use this if you had an abstract base class, like PluginBase, and wanted to call your method on subclasses of PluginBase:

var dataReceiverPlugin = typeLoader.Load<DataLoadingPlugin>(); public class DataLoadingPlugin : PluginBase { } public abstract class PluginBase { }

Note: Constraining to an interface doesn’t allow you to return null – you’ll still have to specify the ‘class’ constraint.

Leave a Comment