There are some great resources on covariance and contravariance here on StackOverflow, but I seem to misunderstand the fundamentals of contravariance. I expect this example to work:
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
A a = new B();
B b = new A();
}
}
public class A
{
int id { get; set; }
}
public class B : A
{
}
Setting a to B works, which is covariance, but setting b to a new A fails with a compile error. Even doing an explicit cast still generates error at compile time. Is there a way to do this or do I just completely misunderstand contravariance?
You can’t do:
Because an
Asimply isn’t aB. The assignment is invalid. I’m not sure I’d even call this variance – it is simply inheritance.In the general case where B had members that A doesn’t, you can see that it makes no sense to do (if
bactually holds a reference to anAobject):where SomeMethod is defined only in B, but this logic extends to the assignment to the variable itself. Even if you added a cast, the cast has an implicit type check that would fail.