Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why is assigning events to variables of type delegate possible in C#?

One way to create an event in C# is as follows:

public event DelegateName EventName

In the above example Delegate name is of type delegate and EventName is of type event. The event needs to know about the signature of the delegates which can be attached to it, but it is not the same type.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

In this example in the Microsoft docs I came across the following:

public event PropertyChangedEventHandler PropertyChanged;

Later on, the following is done:

PropertyChangedEventHandler handler = PropertyChanged;

This is extremely confusing to me. How can a variable of type PropertyChangedEventHandler be assigned an event?

Is there something I am missing here?

>Solution :

How can a variable of type PropertyChangedEventHandler be assigned an event?

Because this is a field-like event. You can only assign to it or read from it within the declaring class itself. Everywhere else, that name refers to the event rather than the field.

From the C# standard section 14.8.2:

Within the program text of the class or struct that contains the declaration of an event, certain events can be used like fields. To be used in this way, an event shall not be abstract or extern, and shall not explicitly include event_accessor_declarations. Such an event can be used in any context that permits a field.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading