Why was IEnumerable made covariant in C# 4?

后端 未结 3 2026
难免孤独
难免孤独 2020-12-01 01:36

In earlier versions of C# IEnumerable was defined like this:

public interface IEnumerable : IEnumerable

Since C# 4 th

3条回答
  •  萌比男神i
    2020-12-01 02:01

    Is it just to make the annoying casts in LINQ expressions go away?

    Not only when using LINQ. It's useful everywhere you have an IEnumerable and the code expects a IEnumerable.

    Won't this introduce the same problems like with string[] <: object[] (broken array variance) in C#?

    No, because covariance is only allowed on interfaces that return values of that type, but don't accept them. So it's safe.

    How was the addition of the covariance done from a compatibility point of view? Will earlier code still work on later versions of .NET or is recompilation necessary here? What about the other way around?

    I think already compiled code will mostly work as is. Some runtime type-checks (is, IsAssignableFrom, ...) will return true where they returned false earlier.

    Was previous code using this interface strictly invariant in all cases or is it possible that certain use cases will behave different now?

    Not sure what you mean by that


    The biggest problems are related to overload resolution. Since now additional implicit conversions are possible a different overload might be chosen.

    void DoSomething(IEnumerabe bla);
    void DoSomething(object blub);
    
    IEnumerable values = ...;
    DoSomething(values);
    

    But of course, if these overload behave differently, the API is already badly designed.

提交回复
热议问题