Duncan Duncan - 1 year ago 172
C# Question

How to make Generic parameter T Nullable in C#?

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


As an example I've created this method
below. This function loops through all of the
items and returns the second smallest item if possible. If this item does not exist it returns

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

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
. So the provided answers there aren't applicable.

Answer Source

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;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download