Interface out T vs T

The out keyword in generics is used to denote that the type T in the interface is covariant.

check following code.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
 
        class Fruit { }
 
        class Banana : Fruit { }
 
        interface ICovariantSkinned<out T> { }
 
        interface ISkinned<T> { }
 
        class A<T> : ISkinned<T> { }
        class B<T> : ICovariantSkinned<T> { }
 
        public static void Main()
        {
            ISkinned<Banana> a1 = new A<Banana>();
            ISkinned<Fruit> a = a1;    // compiling error happens here
 
            ICovariantSkinned<Banana> b1 = new B<Banana>();
            ICovariantSkinned<Fruit> b = b1; // compiling passed
        }
This entry was posted in Uncategorized. Bookmark the permalink.