Home > Software engineering >  Why is assigning events to variables of type delegate possible in C#?
Why is assigning events to variables of type delegate possible in C#?

Time:10-28

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.

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?

CodePudding user response:

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.

  • Related