Generic types with assignable type arguments cannot be assigned themselves.
For example, you cannot use List<string> for List<object> , although string is an object .
It’s not immediately clear why such casting is not supported, so let me give you an example:
var words = new List<string> { "Serve God", "love me", "mend" }; var objects = (List<object>) words;
C # does not encourage an explosion in the Universe, however, with C # 4.0 a light version of this idea is implemented. You see, in some cases, such a cast will be really safe.
.NET 4.0 provides the concepts of covariance and contravariance in generics only for interfaces and delegates , you can check this out.
Example (does not work before .NET 4.0):
void HandleCollection (IEnumerable<object> collection) { // ... } var words = new List<string> { "Serve God", "love me", "mend" }; // IEnumerable is defined as IEnumerable<out T> in .NET 4.0 // 'out' keyword guarantees that T is only used for return values // and therefore client code can't explode the universe var objects = (IEnumerable<object>) words; HandleCollection (objects);
Dan abramov
source share