generic-variance

Why doesn't C# support variant generic classes? [duplicate]

|▌冷眼眸甩不掉的悲伤 提交于 2019-11-29 06:07:35
问题 This question already has answers here : .NET 4.0 Covariance (3 answers) Closed 4 years ago . Take this small LINQPad example: void Main() { Foo<object> foo = new Foo<string>(); Console.WriteLine(foo.Get()); } class Foo<out T> { public T Get() { return default(T); } } It fails to compile with this error: Invalid variance modifier. Only interface and delegate type parameters can be specified as variant. I don't see any logical problem with the code. Everything can be statically verified. Why

Generic Variance in C# 4.0

痞子三分冷 提交于 2019-11-28 05:59:03
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): List<int> intList = new List<int>(); List<object> objectList = intList; [Example non-functional: See Jon Skeet's answer] I recently attended a conference where Jon Skeet gave an excellent overview of Generic Variance, but I'm not sure I'm completely getting it - I understand the significance of the in and out key words when it comes to contra and co-variance, but I'm curious to what happens behind the scenes. What does the CLR see

Generic Variance in C# 4.0

两盒软妹~` 提交于 2019-11-27 01:08:34
问题 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): List<int> intList = new List<int>(); List<object> objectList = intList; [Example non-functional: See Jon Skeet's answer] I recently attended a conference where Jon Skeet gave an excellent overview of Generic Variance, but I'm not sure I'm completely getting it - I understand the significance of the in and out key words when it

How is Generic Covariance & Contra-variance Implemented in C# 4.0?

冷暖自知 提交于 2019-11-26 00:14:37
问题 I didn\'t attend PDC 2008, but I heard some news that C# 4.0 is announced to support Generic covariance and contra-variance. That is, List<string> can be assigned to List<object> . How could that be? In Jon Skeet\'s book C# in Depth , it is explained why C# generics doesn\'t support covariance and contra-variance. It is mainly for writing secure code. Now, C# 4.0 changed to support them. Would it bring chaos? Anybody know the details about C# 4.0 can give some explanation? 回答1: Variance will