Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare nullable types?

I have a few places where I need to compare 2 (nullable) values, to see if they're the same.

I think there should be something in the framework to support this, but can't find anything, so instead have the following:

public static bool IsDifferentTo(this bool? x, bool? y) {     return (x.HasValue != y.HasValue) ? true : x.HasValue && x.Value != y.Value; } 

Then, within code I have if (x.IsDifferentTo(y)) ...

I then have similar methods for nullable ints, nullable doubles etc.

Is there not an easier way to see if two nullable types are the same?

Update:

Turns out that the reason this method existed was because the code has been converted from VB.Net, where Nothing = Nothing returns false (compare to C# where null == null returns true). The VB.Net code should have used .Equals... instead.

like image 658
David_001 Avatar asked Feb 26 '10 12:02

David_001


People also ask

Can you compare null int?

Some int value as an int? is definitely non-null and null is definitely null. The compiler realizes that and since a non-null value is not equal to a definite null value, the warning is given. The compiler also optimizes this away because it is always false. It won't even load the x variable at all.

What is the use of HasValue in C#?

HasValue indicates whether an instance of a nullable value type has a value of its underlying type. Nullable<T>. Value gets the value of an underlying type if HasValue is true . If HasValue is false , the Value property throws an InvalidOperationException.

Which statement is true about nullable type?

Characteristics of Nullable TypesNullable types can only be used with value types. The Value property will throw an InvalidOperationException if value is null; otherwise it will return the value. The HasValue property returns true if the variable contains a value, or false if it is null. You can only use == and !=

What happens when we box or unbox nullable types?

When the nullable type is boxed, the underlying value type is stored in the object, rather than an instance of the nullable type itself. For example, if we box int?, the boxed value will store an int.


1 Answers

C# supports "lifted" operators, so if the type (bool? in this case) is known at compile you should just be able to use:

return x != y; 

If you need generics, then EqualityComparer<T>.Default is your friend:

return !EqualityComparer<T>.Default.Equals(x,y); 

Note, however, that both of these approaches use the "null == null" approach (contrast to ANSI SQL). If you need "null != null" then you'll have to test that separately:

return x == null || x != y; 
like image 111
Marc Gravell Avatar answered Sep 29 '22 11:09

Marc Gravell