15.01.2013 Views

Free-ebooks-library - Bahar Ali Khan

Free-ebooks-library - Bahar Ali Khan

Free-ebooks-library - Bahar Ali Khan

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

t.Names.Add ("test"); // Compiler error<br />

((IList) t.Names).Add ("test"); // NotSupportedException<br />

Plugging in Equality and Order<br />

In the sections “Equality Comparison” on page 245 and “Order Comparison”<br />

on page 255 in Chapter 6, we described the standard .NET protocols that make<br />

a type equatable, hashable, and comparable. A type that implements these protocols<br />

can function correctly in a dictionary or sorted list “out of the box.” More<br />

specifically:<br />

• A type for which Equals and GetHashCode return meaningful results can be used<br />

as a key in a Dictionary or Hashtable.<br />

• A type that implements IComparable /IComparable can be used as a key in<br />

any of the sorted dictionaries or lists.<br />

A type’s default equating or comparison implementation typically reflects what is<br />

most “natural” for that type. Sometimes, however, the default behavior is not what<br />

you want. You might need a dictionary whose string-type key is treated caseinsensitively.<br />

Or you might want a sorted list of customers, sorted by each customer’s<br />

postcode. For this reason, the .NET Framework also defines a matching set of “plugin”<br />

protocols. The plug-in protocols achieve two things:<br />

• They allow you to switch in alternative equating or comparison behavior.<br />

• They allow you to use a dictionary or sorted collection with a key type that’s<br />

not intrinsically equatable or comparable.<br />

The plug-in protocols consist of the following interfaces:<br />

IEqualityComparer and IEqualityComparer<br />

• Performs plug-in equality comparison and hashing<br />

• Recognized by Hashtable and Dictionary<br />

IComparer and IComparer<br />

• Performs plug-in order comparison<br />

• Recognized by the sorted dictionaries and collections; also, Array.Sort<br />

Each interface comes in generic and nongeneric forms. The IEqualityComparer interfaces<br />

also have a default implementation in a class called EqualityComparer.<br />

In addition, Framework 4.0 adds two new interfaces called IStructuralEquatable<br />

and IStructuralComparable, which allow the option of structural comparisons on<br />

classes and arrays.<br />

IEqualityComparer and EqualityComparer<br />

An equality comparer switches in nondefault equality and hashing behavior, primarily<br />

for the Dictionary and Hashtable classes.<br />

304 | Chapter 7: Collections

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!