Information Technology Reference
In-Depth Information
that expects a more base type. For example, Console.WriteLine() has an
overload that takes a System.Object parameter. You can pass an instance of
any type that derives from object. When you override an instance of a
method that returns a System.Object, you can return anything that is
derived from System.Object.
That common behavior led many developers to believe that generics would
follow the same rules. You should be able to use an IEnumerable<MyDerived
Ty p e > w i t h a m e t h o d t h a t h a s a p a r a m e te r o f I E n u m e r a b l e < O b j e c t > . Yo u
would expect that if a method returns an IEnumerable<MyDerivedType>,
you could assign that to a variable of type IEnumerable<object>. No so.
Prior to C# 4.0, all generic types were invariant. That meant there were
many times when you would reasonably expect covariance or contravari-
ance with generics only to be told by the compiler that your code was
invalid. Arrays were treated covariantly. However, Arrays do not support
safe covariance. As of C# 4.0, new keywords are available to enable you to
use generics covariantly and contravariantly. That makes generics much
more useful, especially if you remember to include the in and out param-
eters where possible on generic interfaces and delegates.
Let's begin by understanding the problems with array covariance. Con-
sider this small class hierarchy:
abstract public class CelestialBody
{
public double Mass { get ; set ; }
public string Name { get ; set ; }
// elided
}
public class Planet : CelestialBody
{
// elided
}
public class Moon : CelestialBody
{
// elided
}
 
Search WWH ::




Custom Search