Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a nullable<T> extension method ,how do you do it?

Tags:

c#

nullable

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

like image 793
user9969 Avatar asked Jul 03 '11 07:07

user9969


People also ask

Can you call an extension method on a null object?

As extension methods are in reality static methods of another class, they work even if the reference is null .

How do you make a nullable?

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.

How do you use nullable?

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.

How do you extend a method in C#?

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.


2 Answers

Try this:

public static bool IsLessThan<T>(this Nullable<T> t, Nullable<T> other) where T : struct
{
    return Nullable.Compare(t, other) < 0;
}
like image 142
Sean Thoman Avatar answered Oct 11 '22 06:10

Sean Thoman


It can be simplified:

public static bool IsLessThan<T>(this T? one, T? other) where T : struct
{
    return Nullable.Compare(one, other) < 0;
}
like image 34
Giovani Avatar answered Oct 11 '22 06:10

Giovani