EventHandler without event keyword in C#

Shervan360 1,661 Reputation points
2022-07-27T14:24:14.593+00:00

Hello,

What is the differences between these?
public event EventHandler eEH;
vs
public EventHandler EH;

Thank you

Developer technologies | C#
0 comments No comments
{count} votes

Accepted answer
  1. Reza Aghaei 4,986 Reputation points MVP Volunteer Moderator
    2022-07-27T16:06:35.593+00:00

    What is the differences between these?

    1. public event EventHandler eEH;
    2. public EventHandler EH;

    They are very similar, but different:

    • The first one is an event, the second one is a public field of delegate type.
    • No one can assign a delegate to your event, they only can add (+=) or remove delegates (-=), but in addition to add (+=), and remove (-=), they can assign (=) delegate to the public field.
    • No one can raise event like a delegate outside of your class, but they can invoke your public delegate field.
    • Like properties and methods, you can define events in interfaces but you cannot do the same for fields.

    Example - Difference between an event and a delegate field

    Here are a few examples to demonstrate the differences which I mentioned above:

    • class1.MyEvent = Something; doesn't work.
    • class1.MyDelegateField = Something works and will assign a new multicast delegate to the field.
    • class1.MyEvent(); doesn't work outside of your class.
    • class1.MyDelegateField(); works and will run all the delegates which has been assigned to the field.
    • interface ISomething { event EventHandler MyEvent;} is a valid declaration.
    • interface ISomething { EventHandler MyDelegateField} is invalid.

    More information

    You can learn more about the events:

    3 people found this answer helpful.

1 additional answer

Sort by: Most helpful
  1. Karen Payne MVP 35,586 Reputation points Volunteer Moderator
    2022-07-27T14:27:49.627+00:00

    Why are you not using += and -= see the docs and for all documentation on events see this page.

    2 people found this answer helpful.
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.