17

I have a situation where I need to compare nullable types.
Suppose you have 2 values:

int? foo=null;
int? bar=4;

This will not work:

if(foo>bar)

The following works but obviously not for nullable as we restrict it to value types:

public static bool IsLessThan<T>(this T leftValue, T rightValue) where T : struct, IComparable<T>
{
       return leftValue.CompareTo(rightValue) == -1;
}

This works but it's not generic:

public static bool IsLessThan(this int? leftValue, int? rightValue)
{
    return Nullable.Compare(leftValue, rightValue) == -1;
}

How do I make a Generic version of my IsLessThan?

Thanks a lot

Shadow The GPT Wizard
  • 66,030
  • 26
  • 140
  • 208
user9969
  • 15,632
  • 39
  • 107
  • 175

2 Answers2

23

Try this:

public static bool IsLessThan<T>(this Nullable<T> t, Nullable<T> other) where T : struct
{
    return Nullable.Compare(t, other) < 0;
}
Sean Thoman
  • 7,429
  • 6
  • 56
  • 103
2

It can be simplified:

public static bool IsLessThan<T>(this T? one, T? other) where T : struct
{
    return Nullable.Compare(one, other) < 0;
}
Giovani
  • 21
  • 1