Skip to content

Instantly share code, notes, and snippets.

@illegitimis
Created November 27, 2018 14:18
Show Gist options
  • Save illegitimis/01c2b3cd6bd710c7be38a2cd773a1055 to your computer and use it in GitHub Desktop.
Save illegitimis/01c2b3cd6bd710c7be38a2cd773a1055 to your computer and use it in GitHub Desktop.
Interface Contravariance
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