Event registration, why can the code compile without errors?

I believe there should be many questions regarding SO related to this, but I cannot think of suitable keywords to find them.

Code

class Subscriber
{
    public Subscriber(Notifier n)
    {
        n.OnSomeEvent += (object sender, EventArgs e) => { }; //This does not compile
        n.OnSomeEvent += ReactOnEvent; //This compile successfully!
    }

    private void ReactOnEvent(object sender, EventArgs e)
    {

    }
}

class Notifier
{
    public event EventHandler<MyEventArgs> OnSomeEvent;
    public void Trigger()
    {
        OnSomeEvent?.Invoke(this, new MyEventArgs());
    }
}

class MyEventArgs : EventArgs
{

}

      

Compilation errors for registering a lambda expression make sense.

Error CS1661 Unable to convert lambda expression for delegation of type 'EventHandler <MyEventArgs>' because parameter types do not match delegate parameter types

Error CS1678 Parameter 2 is declared as type "System.EventArgs" but must be "ConsoleApplication1.MyEventArgs"

But why doesn't the compiler give me the same errors for this? Is my understanding of event handling fundamentally wrong? I think the compiler requires the event signature and its handlers to match .

n.OnSomeEvent += ReactOnEvent;

      

Edit:

As Peter pointed out in his comments and quoted by ms docs ,

(since .NET 3.5) ... you can assign delegates not only methods with matching signatures, but also methods that return more derived types (covariance) or take parameters that have less derived types (contravariance) than those specified by the delegate type ...

+3


source to share


1 answer


when using a lambda expression, the input parameters are output by the compiler.

n.OnSomeEvent + = (sender, e) => {};



mouse over the sender and e and you should notice that they are of the correct types required for OnSomeEvent

A quick example on using lambda expressions to subscribe to events can be found here: https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/statements-expressions-operators/how-to-use-lambda -expressions-outside-linq

-1


source







All Articles