Volume 4
Volume 4, Number 36 |
July 19, 2006 |
|
Robert Dollinger
|
Abstract: Overriding Equals() in order to provide meaningful semantics to object comparisons, turns out to be quite a challenging task, especially when involving objects at different levels of a class hierarchy. One need to reconcile the requirements of the equals contract with the legitimate expectations of programmers of being able to meaningfully compare objects of different types. Langer&Kreft (Langer, 2002b) provided an implementation of equality checks for Java class hierarchies where they use a recursive navigation method that performs the non-trivial task of navigating up and down in the inheritance tree in order to make sure that objects on different levels or even on different branches of the inheritance tree are compared correctly. In this paper we first present a generalized implementation of the navigation method by using reflection and late binding techniques available in C# .NET. In this implementation navigation is still using recursion very much like the one in (Langer, 2002b). A non-recursive version of the navigation method is also given; this later version is more efficient and easier to understand. The generalized implementation of the navigation method is class independent and, as a result, one can factor it out to the hierarchy's root class. If it would be implemented in the very top class of the .NET hierarchy, the Object class, this would simply make mixed-type equality comparisons generally available by requiring classes to implement some sort of field comparing method thus defining the specific equality semantics, instead of struggling to override the Equals() method.
Keywords: : equals contract, mixed-type comparisons, reflection, late binding
Download this issue: ISEDJ.4(36).Dollinger.pdf (Adobe PDF, 13 pages, 749 K bytes)
Preview the contents: Dollinger.j.txt (ASCII txt, 35 K bytes)
Recommended Citation: Dollinger (2006). A Solution to Mixed-type Comparisons in C# .NET. Information Systems Education Journal, 4 (36). http://isedj.org/4/36/. ISSN: 1545-679X. (A preliminary version appears in The Proceedings of ISECON 2005: §2554. ISSN: 1542-7382.)