Help with C# generics error - "The type 'T' must be a non-nullable value type"

C#Generics

C# Problem Overview


I'm new to C# and don't understand why the following code doesn't work.

public static Nullable<T> CoalesceMax<T>(Nullable<T> a, Nullable<T> b) where T : IComparable
{
    if (a.HasValue && b.HasValue)
        return a.Value.CompareTo(b.Value) < 0 ? b : a;
    else if (a.HasValue)
        return a;
    else
        return b;
}

// Sample usage:
public DateTime? CalculateDate(DataRow row)
{
    DateTime? result = null;
    if (!(row["EXPIRATION_DATE"] is DBNull))
        result = DateTime.Parse((string)row["EXPIRATION_DATE"]);
    if (!(row["SHIPPING_DATE"] is DBNull))
        result = CoalesceMax(
            result
            DateTime.Parse((string)row["SHIPPING_DATE"]).AddYears(1));
    // etc.
    return result;
}

It gives the following error during compilation:

The type 'T' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'System.Nullable<T>'

C# Solutions


Solution 1 - C#

You need to add a T : struct constraint:

public static Nullable<T> CoalesceMax<T>
    (Nullable<T> a, Nullable<T> b) where T : struct, IComparable

Otherwise C# will try to work out what Nullable<T> means, and realise that it doesn't already have the constraint required by Nullable<T> itself. In other words, you could try to call:

CoalesceMax<string>(...)

which wouldn't make sense, as Nullable<string> isn't valid.

Solution 2 - C#

The Nullable<T> type has a constraint on it that requires T to be a value type (struct in C#). That's why the compiler is telling you about Nullable<T> and not your function or the call site of that function -- it's the Nullable class that is the root cause of the error, so this is actually more helpful that if the compiler just pointed to your function and said "this ain't right, fix it!" (Imagine if CoalesceMax used several generics, and violated the constraint on only one of them - it's more useful to know which generic had its constraint broken than to just know that one or more constraints in CoalesceMax were broken).

The solution is to make your T and their T compatible by introducing the same constraint. This is done by adding the struct constraint, which must come before all interface / new constraints:

public static Nullable<T> CoalesceMax<T>(Nullable<T> a, Nullable<T> b) where T : struct, IComparable{
  ...
}

Solution 3 - C#

Your generic method is using a Nullable<T>.

However, you aren't constraining the type of T, so it could end up being Nullable<Form>, which is obviously invalid.

You need to change the constraint to where T : struct, IComparable to ensure that T can only be a value type.

Solution 4 - C#

Not exactly an answer to the OP but since this was the first thing that popped up on google for the same error message, I had to add the constraint on my class definition, rather than my method, eg

public class MyClass<T> where T : struct
{
    public void MyMethod(T? value)
    {
    }
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJosh KelleyView Question on Stackoverflow
Solution 1 - C#Jon SkeetView Answer on Stackoverflow
Solution 2 - C#user197015View Answer on Stackoverflow
Solution 3 - C#SLaksView Answer on Stackoverflow
Solution 4 - C#3-14159265358979323846264View Answer on Stackoverflow