Prev | Current Page 174 | Next

Jon Skeet

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


This is not just specific to operators??”when the compiler encounters a
generic type, it resolves all the method overloads when compiling
the unbound generic type, rather than reconsidering each possible
method call for more specific overloads at execution time. For instance, a
statement of Console.WriteLine (default(T)); will always resolve to call
Console.WriteLine(object value)??”it doesn??™t call Console.WriteLine
(string value) when T happens to be string. This is similar to the normal
situation of overloads being chosen at compile time rather than execution
time, but readers familiar with templates in C++ may be surprised nonetheless.
Two classes that are extremely useful when it comes to comparing values are Equality-
Comparer and Comparer, both in the System.Collections.Generic namespace.
They implement IEqualityComparer (useful for comparing and hashing dictionary
keys) and IComparer (useful for sorting) respectively, and the Default property
returns an implementation that generally does the right thing for the appropriate type.
See the documentation for more details, but consider using these (and similar types
such as StringComparer) when performing comparisons. We??™ll use Equality-
Comparer in our next example.
FULL COMPARISON EXAMPLE: REPRESENTING A PAIR OF VALUES
To finish off our section on implementing generics??”and indeed ???medium-level??? generics
??”here??™s a complete example.


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