0

I have these two sample classes:

void Main()
{
    Provider1 myProvider1 = new Provider1();
    myProvider1.MyEvent += (sender, eventData) => Console.WriteLine($"the event1 handled : {eventData.Data}");

    myProvider1.DoSth();

    //
    Provider2 myProvider2 = new Provider2();
    myProvider2.MyEvent = (sender, eventData) => Console.WriteLine($"the event2 handled : {eventData.Data}");

    myProvider2.DoSth();
}

public class SampleEventArgs : EventArgs
{
    public string Data { get; }
    public SampleEventArgs(string data)
    {
        Data = data;
    }
}

public class Provider1
{
    public event EventHandler<SampleEventArgs> MyEvent;

    public void DoSth()
    {
        MyEvent?.Invoke(this, new SampleEventArgs("TestData"));
    }
}

public class Provider2
{
    public Action<object, SampleEventArgs> MyEvent;
    public void DoSth()
    {
        MyEvent?.Invoke(this, new SampleEventArgs("TestData"));
    }
}

Provider1 has a event MyEvent and Provider2 has a Action<object> MyEvent (to act just like the event in Provider1). I can achieve the same result from both of them, but I want to know when to use each pattern and why (I know that Action is just a delegate).

Updated based on comments

TheMah
  • 378
  • 5
  • 19
  • 1
    en `event` is also just a `delegate`, or more precise: what a property is for a field, that is what an event is for a delegate. Having said this, an event has a fix signature: it expects a sender-object and some event-args. An `Action` on the other hand does not expect anything, unless you use an `Action`. So this is actually a question about when to use an event instead of a delegate. – MakePeaceGreatAgain Dec 19 '22 at 15:59
  • @MakePeaceGreatAgain okay, so as you said, I updated my question to ask a correct question – TheMah Dec 19 '22 at 16:06

0 Answers0