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
As extension methods are in reality static methods of another class, they work even if the reference is null .
You can declare nullable types using Nullable<t> where T is a type. Nullable<int> i = null; A nullable type can represent the correct range of values for its underlying value type, plus an additional null value. For example, Nullable<int> can be assigned any value from -2147483648 to 2147483647, or a null value.
You typically use a nullable value type when you need to represent the undefined value of an underlying value type. For example, a Boolean, or bool , variable can only be either true or false . However, in some applications a variable value can be undefined or missing.
Extension methods are defined as static methods but are called by using instance method syntax. Their first parameter specifies which type the method operates on. The parameter is preceded by the this modifier.
Try this:
public static bool IsLessThan<T>(this Nullable<T> t, Nullable<T> other) where T : struct
{
return Nullable.Compare(t, other) < 0;
}
It can be simplified:
public static bool IsLessThan<T>(this T? one, T? other) where T : struct
{
return Nullable.Compare(one, other) < 0;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With