Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Raising events by calling delegates - why not by event name?

Tags:

c#

events

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/

like image 352
User039402 Avatar asked Aug 20 '17 06:08

User039402


People also ask

What is the main difference between the event and delegate?

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.

How events are handled through 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.

Why do we need events when we have delegates?

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.

Can we use events without delegates?

Yes, you can declare an event without declaring a delegate by using Action.


1 Answers

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);
like image 190
areller Avatar answered Oct 10 '22 20:10

areller