Why can I not assign a List of concrete types to a List of that concrete's interface?

前端 未结 8 1502
悲哀的现实
悲哀的现实 2020-12-19 02:17

Why does this not compile?

public interface IConcrete { }

public class Concrete : IConcrete { }

public class Runner
{
    public static void Main()
    {
         


        
8条回答
  •  轮回少年
    2020-12-19 03:05

    Currently, this is forbidden because otherwise the type safety would be broken. you could do something like this inside of DoStuffWithInterfaceList:

    public class OtherConcrete : IConcrete { }
    
    public void DoStuffWithInterfaceList(List listOfInterfaces) 
    {
           listOfInterfaces.Add(new OtherConcrete ());
    }
    

    Which will fail at run time because listOfInterfaces is of type Concrete only.

    As others said, this will be possible is C# 4 as long as you don't change the list inside the method but you'll have to explicitly tell it to the compiler.

    To answer your other question about converting the list, If you're using .Net 3.5 I would go with Enumerable.Cast<> extension method. otherwise, you can write a lazy conversion method yourself using the yield keyword, which will give you the same effect.

    EDIT:

    As Eric Lippert said, you should use IEnumerable in order for it to work in C# 4.

提交回复
热议问题