Why does this not work? Do I not understand delegate covariance correctly?
public delegate void MyDelegate(object obj)
public class MyClass
{
public MyClass()
{
//Error: Expected method with 'void MyDelegate(object)' signature
_delegate = MyMethod;
}
private MyDelegate _delegate;
public void MyMethod(SomeObject obj)
{}
}
Correct – you don’t understand covariance correctly – yet 🙂 Your code would work if you had the same types but as return values, like this:
That would demonstrate covariance. Alternatively, you can keep it as parameters but switch the types around:
This now demonstrates contravariance.
My rule of thumb is to ask myself, “given the delegate, what could I do with it? If I can pass in an argument which would break the method, the conversion should have failed. If the method can return something which would break the caller, the conversion should have failed.”
In your code, you could have called:
At that point, poor
MyMethodhas a parameter which is meant to be of typeSomeObject, but is actually of typeobject. This would be a Very Bad Thing, so the compiler stops it from happening.Does that all make more sense?