Invariance C# with Example



Invariance C# with Example

IList is never a subtype of a different IList. IList is invariant in its type parameter. 
class Animal { /* ... */ } 
class Dog : Animal { /* ... */ } 
IList dogs = new List(); 
IList animals = dogs; // type error 
There is no subtype relationship for lists because you can put values into a list and take values out of a list. 
If IList was covariant, you'd be able to add items of the wrong subtype to a given list. 
IList animals = new List(); // supposing this were allowed... 
animals.Add(new Giraffe()); // ... then this would also be allowed, which is bad! 
If IList was contravariant, you'd be able to extract values of the wrong subtype from a given list. 
IList dogs = new List { new Dog(), new Giraffe() }; // if this were allowed... 
Dog dog = dogs[1]; // ... then this would be allowed, which is bad! 
Invariant type parameters are declared by omitting both the in and out keywords. 
interface IList { /* ... */ } 

0 Comment's

Comment Form

Submit Comment