Last active
September 19, 2021 20:15
-
-
Save bjorn-einar-bjartnes-4ss/9c7dd9f3bdda678f854a1e3385796093 to your computer and use it in GitHub Desktop.
Covariance
This file contains hidden or 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.Collections.Generic; | |
using System.Linq; | |
namespace Covariance | |
{ | |
interface IMyFace { string Title { get; } } | |
class MyFace: IMyFace { public string Title => "This is my face"; } | |
class YourFace : IMyFace { public string Title => "And your face"; } | |
public class Example | |
{ | |
private static void AddToMe(List<IMyFace> list) => list.Add(new YourFace() ); | |
private static IMyFace FirstOrNull(IEnumerable<IMyFace> list) => list.FirstOrDefault(); | |
public void Examples() | |
{ | |
var foo = new List<IMyFace> {new MyFace(), new MyFace()}; | |
var foo2 = new List<IMyFace> {new MyFace(), new MyFace(), new YourFace()}; | |
var foo3 = new List<MyFace> {new MyFace(), new MyFace() }; | |
AddToMe(foo); | |
AddToMe(foo2); | |
FirstOrNull(foo3); // OK because it is only pulling things out | |
// AddToMe(foo3); Not OK because we can put YourFace in a MyFace list | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment