David_001
David_001

Reputation: 5802

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.

Upvotes: 82

Views: 65893

Answers (8)

Anton Gogolev
Anton Gogolev

Reputation: 115741

You can use Nullable.Equals<T>.

Upvotes: 49

Kashif
Kashif

Reputation: 14430

You can just use the Equals method of Nullable<T>:

bool areDifferent = x.Equals(y);

Your method is redundant

Your method is then simplified to:

public static bool IsDifferentTo(this bool? x, bool? y) => !x.Equals(y);

Which is redundant to just calling equals:

  • one.IsDifferentTo(other) is the same as !one.Equals(other).
  • IsDifferentTo(one, other) is the same as !Nullable.Equals(one,other).

Safety from NullReferenceExceptions

This will not throw a NullReferenceException because a int?, synonym of Nullable<int>, is a struct — a value type, not a reference type. You can test this quickly:

Nullable<int> test = null;
// result is false; no NullReferenceException is thrown.
bool isNull = test.HasValue;

Upvotes: 34

Genius_x
Genius_x

Reputation: 35

(x?? 0).Equals(y)

will handle null as well as equals.

Upvotes: -1

hdd42
hdd42

Reputation: 66

I wanted to find how to compare two nullable int on C#, but I always get this link after search, so if someone needs to compare exactly two nullable int, then this can be helpful

a.GetValueOrDefault(int.MinValue).CompareTo(b.GetValueOrDefault(long.MinValue));

Upvotes: 3

Marc Gravell
Marc Gravell

Reputation: 1062770

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;

Upvotes: 93

Lucero
Lucero

Reputation: 60190

Just use ==, or .Equals().

Upvotes: 6

Mark Seemann
Mark Seemann

Reputation: 233150

You can use the static Equals method on System.Object:

var equal = object.Equals(objA, objB);

Upvotes: 6

Related Questions