C# List: why you cannot do `List foo = new List();`

前端 未结 9 1019
我在风中等你
我在风中等你 2020-12-02 20:05

If you have an Interface IFoo and a class Bar : IFoo, why can you do the following:

List foo = new List();          


        
9条回答
  •  悲&欢浪女
    2020-12-02 20:32

    The reason is that C# does not support co- and contravariance for generics in C# 3.0 or earlier releases. This is being implemented in C# 4.0, so you'll be able to do the following:

    IEnumerable foo = new List();
    

    Note that in C# 4.0, you can cast to IEnumerable, but you won't be be able cast to List. The reason is due to type safety, if you were able to cast a List to List you would be able to add other IFoo implementors to the list, breaking type safety.

    For more background on covariance and contravariance in C#, Eric Lippert has a nice blog series.

提交回复
热议问题