Skip to content
Browse files

Fix handling of null in the non generic implementation of EqualityCom…

…parer. Fixes 703027.
  • Loading branch information...
1 parent af6f63e commit 648425ebe1af72b062b1810e86ada260be9104f0 @jbevain jbevain committed Jun 30, 2011
Showing with 12 additions and 1 deletion.
  1. +12 −1 mcs/class/corlib/System.Collections.Generic/EqualityComparer.cs
View
13 mcs/class/corlib/System.Collections.Generic/EqualityComparer.cs
@@ -45,7 +45,6 @@ static EqualityComparer ()
_default = new DefaultComparer ();
}
-
public abstract int GetHashCode (T obj);
public abstract bool Equals (T x, T y);
@@ -59,11 +58,23 @@ static EqualityComparer ()
int IEqualityComparer.GetHashCode (object obj)
{
+ if (obj == null)
+ return 0;
+
+ if (!(obj is T))
+ throw new ArgumentException ("Argument is not compatible", "obj");
+
return GetHashCode ((T)obj);
}
bool IEqualityComparer.Equals (object x, object y)
{
+ if (x == y)
+ return true;
+
+ if (x == null || y == null)
+ return false;
+
if (!(x is T))
throw new ArgumentException ("Argument is not compatible", "x");
if (!(y is T))

2 comments on commit 648425e

@sehe
sehe commented on 648425e Jul 4, 2011

I just noted something else here; I was looking at the code due to this StackOverflow answer by Marc Gravell.

From inspecting the IL generated in GenericEqualityComparer<T>.Equals I spotted boxing occurring (due to comparing to null?). Wouldn't it be even better to have a separate default GenericStructComparer<T> implementation to be used for value-types that implement IEquatable?

@myeisha
myeisha commented on 648425e Jul 4, 2011

Then one would need a GenericClassEqualityComparer<T> where T : class, IEquatable<T> and GenericStructEqualityComparer<T> where T : struct, IEquatable<T>. One case wouldn't need null checking, the other wouldn't need boxing.

Please sign in to comment.
Something went wrong with that request. Please try again.