Created
November 27, 2018 14:18
-
-
Save illegitimis/01c2b3cd6bd710c7be38a2cd773a1055 to your computer and use it in GitHub Desktop.
Interface Contravariance
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
public interface IContravariantExample<in T> | |
{ | |
string Go(T t); | |
} | |
public class ContravariantExample<T> : IContravariantExample<T> | |
{ | |
public string Go(T t) => $"{nameof(ContravariantExample<T>)} {typeof(T).Name} {t.GetType().Name} {t}"; | |
} | |
[Fact] | |
public void InterfaceContraVariance() | |
{ | |
object o = "13"; | |
IContravariantExample<object> ino = new ContravariantExample<object>(); | |
IContravariantExample<string> ins = ino; | |
const string expected = "ContravariantExample Object String 13"; | |
string s1 = ino.Go(o); | |
Assert.Equal(expected, s1); | |
string s2 = ins.Go(o as string); | |
Assert.Equal(expected, s2); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment