Information Technology Reference
In-Depth Information
Eventually, people consume the information in your types. People under-
stand text output, so you want to provide it in the simplest fashion possi-
ble: Override ToString() in all your types. Make the ToString() output
short and reasonable.
Item 6: Understand the Relationships Among the Many
Different Concepts of Equality
When you create your own types (either classes or structs ), you define
what equality means for that type. C# provides four different functions
that determine whether two different objects are “equal”:
public static bool ReferenceEquals
( object left, object right);
public static bool Equals
( object left, object right);
public virtual bool Equals( object right);
public static bool operator ==( MyClass left, MyClass right);
The language enables you to create your own versions of all four of these
methods. But just because you can doesn't mean that you should. You
should never redefine the first two static functions. You'll often create your
own instance Equals() method to define the semantics of your type, and
you'll occasionally override operator==(), typically for performance rea-
sons in value types. Furthermore, there are relationships among these four
functions, so when you change one, you can affect the behavior of the oth-
ers. Yes, needing four functions to test equality is complicated. But don't
worry—you can simplify it.
Of course, those four methods are not the only options for equality. Types
that override Equals() should implement IEquatable<T>. Types that
implement value semantics should implement the IStructuralEquality
interface. That means six different ways to express equality.
Like so many of the complicated elements in C#, this one follows from the
fact that C# enables you to create both value types and reference types.
Tw o v a r i a b l e s o f a r e f e r e n c e t y p e a r e e q u a l i f t h e y r e f e r t o t h e s a m e o b j e c t ,
referred to as object identity. Two variables of a value type are equal if they
are the same type and they contain the same contents. That's why equal-
ity tests need so many different methods.
 
 
Search WWH ::




Custom Search