Created
October 1, 2019 04:55
Star
You must be signed in to star a gist
Generic covariance in C#
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
namespace ConsoleApp6 | |
{ | |
class Program | |
{ | |
public interface IBar | |
{ | |
// .... | |
} | |
public class Bar1 : IBar | |
{} | |
public class Bar2 : IBar | |
{ } | |
public static void Foo1(List<IBar> barList, IBar value) => | |
barList.Add(value); | |
public static void Foo2(IReadOnlyList<IBar> barList, IBar value) => | |
barList.Add(value); // Add method not found | |
static void Main(string[] args) | |
{ | |
Foo1(new List<IBar>(), new Bar1()); // Valid | |
Foo1(new List<IBar>(), new Bar2()); // Valid | |
Foo1(new List<Bar1>(), new Bar1()); // Cannot convert | |
Foo1(new List<Bar2>(), new Bar2()); // Cannot convert | |
Foo2(new List<Bar1>(), new Bar1()); // Valid | |
Foo2(new List<Bar2>(), new Bar2()); // Valid | |
Foo2(new List<Bar1>(), new Bar2()); // Valid? (new List<Bar1>().Add(new Bar2())) | |
Foo2(new List<Bar2>(), new Bar1()); // Valid? (new List<Bar2>().Add(new Bar1())) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment