Skip to content

Instantly share code, notes, and snippets.

@kekyo
Created October 1, 2019 04:55
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save kekyo/b7155ba867b4ae3f2712bcef36283059 to your computer and use it in GitHub Desktop.
Generic covariance in C#
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