views:

286

answers:

6

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.

A: 

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

var equal = object.Equals(objA, objB);
Mark Seemann
+3  A: 

Nullable.Equals<T>?

Anton Gogolev
A: 

Use Compare:

http://msdn.microsoft.com/en-us/library/dxxt7t2a.aspx

Randy Minder
You don't need compare to check for equality; this is only needed for real comparison such as for sorting.
Lucero
+2  A: 

Just use ==, or .Equals().

Lucero
+7  A: 

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;
Marc Gravell
A: 
if (x.Equals(y)) 
Muhammad Kashif Nadeem
Can you please tell me why this downvote. Just wanted to know where I am wrong.
Muhammad Kashif Nadeem
I didn't downvote you, but what happens if x is null? Invoking a method on a null reference would probably result in a NullReferenceException.
Chris Shouts