Duncan Duncan - 2 months ago 9
C# Question

How to make Generic parameter T Nullable in C#?

I'm creating a generic method which should be able to return

null
.

As an example I've created this method
GetSecondSmallest(List<T>)
below. This function loops through all of the
IComparable
items and returns the second smallest item if possible. If this item does not exist it returns
null
.

public T? GetSecondSmallest<T>(List<T> items) where T : Nullable, IComparable
{
if (items.Count == 0) return null;

T smallest = items[0];
T? secondSmallest = null;

// Find second smallest by looping through list

return secondSmallest;
}


Two example usages of this method would be:

GetSecondSmallest(new List<int> {4, 2, 3, 1, 6, 8}) // Should return 2
GetSecondSmallest(new List<MyComparable> {new MyComparable('x')}) // Should return null


When you try to compile this code you'll see what the problem is here:


Error CS0717 'Nullable': static classes cannot be used as constraints


How can I make this method return either an instance of
T
or
null
?




EDIT: I have already seen this question, but this does not answer my question, because in my situation the parameter is also generic, and should be
Nullable
. So the provided answers there aren't applicable.

Answer

You can't narrow T down as nullable or an object. You have to make two methods, one for T and one for T?.

public T? GetSecondSmallestAsNullable<T>(List<T> items) where T : struct
{
    return null;
}

public T GetSecondSmallestAsClass<T>(List<T> items) where T : class
{
    return null;
}