There is something I am not understanding about covariance and contravariance of delegates. What's the rationale behind flexibility to downcast parameters and to upcast return types
As an example, say we have
- Person as a Superclass and Teacher as a Subclass of Person
- ReturnPersonDelagate that represents a method that returns a person
- TeacherParameterDelegate that represents method that take an employee object as a parameter
You can
- assign a method that return a Teacher to ReturnPersonDelagate (upcasting)
- assign a method that takes Person as a parameter TeacherParameterDelegate (downcasting)
I am a bit confused. What's the rationale behind this concept and why is downcasting supported implicitly?
It makes perfect sense. Take a look:
Method
returns aTeacher
object which is always of typePerson
but imagine you swap the types and make theDel
return a more specific type andMethod
to return a more general type. The code would not work and would not make sense at all. But in this case, it does as you always get a correct type that can be converted implicitly to the return type of theDel
. Also, the type of the parameter of theDel
type is more specific than the oneMethod
accepts as it also makes sense. If you would swap them for example you could invoke theMethod
with the incorrect type but in this case, it is fine as theTeacher
object will always be of typePerson
.