Prev | Current Page 172 | Next

Jon Skeet

"C# in Depth: What you need to master C# 2 and 3"


Don??™t worry about it for the moment??”there??™s an alternative using IComparer, as
we??™ll see soon.
DIRECT COMPARISONS
Although listing 3.4 showed how a comparison is possible, we don??™t always want to constrain
our types to implement IComparable or its sister interface, IEquatable,
which provides a strongly typed Equals(T) method to complement the Equals(object)
method that all types have. Without the extra information these interfaces give us access
to, there is little we can do in terms of comparisons, other than calling Equals(object),
which will result in boxing the value we want to compare with when it??™s a value type.
(In fact, there are a couple of types to help us in some situations??”we??™ll come to them
in a minute.)
When a type parameter is unconstrained (in other words, no constraints are applied
to it), you can use == and != operators but only to compare a value of that type with
null. You can??™t compare two values of T with each other. In the case where the type
argument provided for T is a value type (other than a nullable type), a comparison with
null will always decide they are unequal (so the comparison can be removed by the JIT
compiler). When the type argument is a reference type, the normal reference comparison
will be used. When the type argument is a nullable type, the comparison will do the
obvious thing, treating an instance without a value as null.


Pages:
160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184