Monday 17 December 2012

c sharp programming

IStructuralEquatable and IStructuralComparable
As we said in the previous chapter, structs implement structural comparison by de-
fault: two structs are equal if all of their fields are equal. Sometimes, however, struc-
tural equality and order comparison are useful as plug-in options on other types as
well—such as arrays and tuples. Framework 4.0 introduces two new interfaces to
help with this:
public interface IStructuralEquatable
{
  bool Equals (object other, IEqualityComparer comparer);
  int GetHashCode (IEqualityComparer comparer);
}
public interface IStructuralComparable
{
  int CompareTo (object other, IComparer comparer);
}
The IEqualityComparer/IComparer  that you pass  in are applied  to each  individual
element in the composite object. We can demonstrate this using arrays and tuples,
which implement these interfaces: in the following example, we compare two arrays
for equality: first using the default Equals method, and then using IStructuralEquat
able’s version:
int[] a1 = { 1, 2, 3 };
int[] a2 = { 1, 2, 3 };
Console.Write (a1.Equals (a2));                                 // False
Console.Write (a1.Equals (a2, EqualityComparer<int>.Default));  // True

Here’s another example:
string[] a1 = "the quick brown fox".Split();
string[] a2 = "THE QUICK BROWN FOX".Split();
bool isTrue = a1.Equals (a2, StringComparer.InvariantCultureIgnoreCase);
Tuples work in the same way:
var t1 = Tuple.Create (1, "foo");
var t2 = Tuple.Create (1, "FOO");
bool isTrue = t1.Equals (t2, StringComparer.InvariantCultureIgnoreCase);
int zero = t1.CompareTo (t2, StringComparer.InvariantCultureIgnoreCase);
The difference with tuples, though, is that their default equality and order compar-
ison implementations also apply structural comparisons:
var t1 = Tuple.Create (1, "FOO");
var t2 = Tuple.Create (1, "FOO");
Console.WriteLine (t1.Equals (t2));   // True

No comments:

Post a Comment