Prev | Current Page 216 | Next

Jon Skeet

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

I know that adding a constraint makes it sound less
general, but the generality is added by first making the type or method generic. When
you run into a problem like this, adding a level of genericity somewhere with an
appropriate constraint should be the first option to consider. Generic methods (rather
than generic types) are often helpful here, as type inference can make the lack of variance
invisible to the naked eye. This is particularly true in C# 3, which has stronger
type inference capabilities than C# 2.
NOTE Is this really the best we can do???”As we??™ll see later, Java supports covariance
and contravariance within its generics??”so why can??™t C#? Well, a lot of it
boils down to the implementation??”the fact that the Java runtime
doesn??™t get involved with generics; it??™s basically a compile-time feature.
However, the CLR does support limited generic covariance and contravariance,
just on interfaces and delegates. C# doesn??™t expose this feature
(neither does VB.NET), and none of the framework libraries use it. The
C# compiler consumes covariant and contravariant interfaces as if they
were invariant. Adding variance is under consideration for C# 4,
although no firm commitments have been made. Eric Lippert has written
a whole series of blog posts about the general problem, and what might
happen in future versions of C#: http://blogs.


Pages:
204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228