Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

generics

People also ask

Is C easy for beginners?

Which programming language is easy to learn? C and C++ are both somewhat difficult to learn to program well. However, in many respects, they share many similarities with many other popular languages. In that sense they're just as easy (or as difficult) to learn, at first, as anything other programming language.

Is C hard to learn for beginners?

C is more difficult to learn than JavaScript, but it's a valuable skill to have because most programming languages are actually implemented in C. This is because C is a “machine-level” language. So learning it will teach you how a computer works and will actually make learning new languages in the future easier.


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.


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{
  ...
}

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.


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)
    {
    }
}