I have looking at an old piece of code and cannot somehow understand the following:
public event EventHandler NameChanged;
#endregion
#region protected void OnNameChanged(EventArgs args)
/// <summary>
/// Raises NameChanged event.
/// </summary>
/// <param name="args">Event arguments.</param>
protected void OnNameChanged(EventArgs args)
{
EventHandler eh = this.NameChanged;
if (eh != null)
{
eh(this, args);
}
}
Why is the event raised by an invocation of the delegate? Could I not simply call the event itself (NameChanged) as usual?
EDIT: I can see this is also suggested on MSDN: https://docs.microsoft.com/en-us/dotnet/standard/events/
Delegate is a function pointer. It holds the reference of one or more methods at runtime. Delegate is independent and not dependent on events. An event is dependent on a delegate and cannot be created without delegates.
Using Delegates with EventsThe events are declared and raised in a class and associated with the event handlers using delegates within the same class or some other class. The class containing the event is used to publish the event. This is called the publisher class.
The main purpose of events is to prevent subscribers from interfering with each other. If you do not use events, you can: Replace other subscribers by reassigning delegate(instead of using the += operator), Clear all subscribers (by setting delegate to null), Broadcast to other subscribers by invoking the delegate.
Yes, you can declare an event without declaring a delegate by using Action.
Whenever you reference an event, you are in fact copying the invocation list to the local reference.
By doing that, you make sure that between checking the validity of the event eh != null
and invoking the event eh(this, args)
eh's value wouldn't change (maybe from a different thread).
In C# 6, there is a new operator https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/operators/null-conditional-operators
You could just do this instead:
NameChanged?.Invoke(this, args);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With