Sipo Sipo - 1 month ago 16
C# Question

Why forcing an event's subscribers to have a specific signature in C#?

Declaring an event requires a delegate that the subscribers will follow (as far as I know):

public delegate void SomeEventHandler(object source, EventArgs args);
public event SomeEventHandler EventHappend;


But why do we need this delegate? Why don't let any method with any signature to subscribe to the event?

Answer

Keeping your example...

class A
{
  public event EventHappend; // Invalid C# but let's pretend it could work

  public void DoSomething()
  {
    ...
    if (EventHappend != null)
    {
      // What should ??? be replaced with?
      EventHappend(???);
    }
  }
}

class B
{
  public B()
  {
    new A().EventHappend += EventHandler;
  }

  public void EventHandler(int anInt)
  ...
}

class C
{
  public C()
  {
    new A().EventHappend += EventHandler;
  }

  public void EventHandler(string aString)
  ...
}

What should ??? be replaced with to handle B and C's case (int or string in parameter)?