Generic Variance in C# 4.0

前端 未结 3 1207
孤城傲影
孤城傲影 2020-12-08 11:20

Generic Variance in C# 4.0 has been implemented in such a way that it\'s possible to write the following without an exception (which is what would happen in C# 3.0):

3条回答
  •  [愿得一人]
    2020-12-08 11:59

    Out of interest, why wasn't this introduced in previous versions

    The first versions (1.x) of .NET didn't have generics at all, so generic variance was far off.

    It should be noted that in all versions of .NET, there is array covariance. Unfortunately, it's unsafe covariance:

    Apple[] apples = new [] { apple1, apple2 };
    Fruit[] fruit = apples;
    fruit[1] = new Orange(); // Oh snap! Runtime exception! Can't store an orange in an array of apples!
    

    The co- and contra-variance in C# 4 is safe, and prevents this problem.

    what's the main benefit - ie real world usage?

    Many times in code, you are calling an API expects an amplified type of Base (e.g. IEnumerable) but all you've got is an amplified type of Derived (e.g. IEnumerable).

    In C# 2 and C# 3, you'd need to manually convert to IEnumerable, even though it should "just work". Co- and contra-variance makes it "just work".

    p.s. Totally sucks that Skeet's answer is eating all my rep points. Damn you, Skeet! :-) Looks like he's answered this before, though.

提交回复
热议问题