(Don??™t worry if this last bit
doesn??™t make sense yet??”it will when you??™ve read the next chapter. Some features are
too intertwined to allow me to describe either of them completely without referring to
the other, unfortunately.)
When a type parameter is constrained to be a value type, == and != can??™t be used with
it at all. When it??™s constrained to be a reference type, the kind of comparison performed
depends on exactly what the type parameter is constrained to be. If it??™s just a reference
type, simple reference comparisons are performed. If it??™s further constrained to
83 Beyond the basics
derive from a particular type that overloads the == and != operators, those overloads are
used. Beware, however??”extra overloads that happen to be made available by the type
argument specified by the caller are not used. Listing 3.5 demonstrates this with a simple
reference type constraint and a type argument of string.
static bool AreReferencesEqual
(T first, T second)
where T : class
{
return first==second;
}
...
string name = "Jon";
string intro1 = "My name is "+name;
string intro2 = "My name is "+name;
Console.WriteLine (intro1==intro2);
Console.WriteLine (AreReferencesEqual(intro1, intro2));
Even though string overloads == (as demonstrated by C printing True), this overload
is not used by the comparison at B. Basically, when AreReferencesEqual is compiled
the compiler doesn??™t know what overloads will be available??”it??™s as if the parameters
passed in were just of type object.
Pages:
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185