0

I am learning programming (self learning with online resources) and I came across this bit of code. I have hard time understanding it. I do not understand only last line OnItemAdded?.Invoke(this, item)

public async Task AddItem(TodoItem item)
{
   await CreateConnection();
   await connection.InsertAsync(item);
   OnItemAdded?.Invoke(this, item);
}

I searched and read many resources (on MSN and here) and if I understand this correctly then this part of code checks if OnItemAdded is not null, then this part of code is executed again? And OnItemAdded is not null in case it failed to add item to list? Do I read and understand this line correctly?

Sh.Imran
  • 1,035
  • 7
  • 13
Bumbar
  • 5
  • 7
  • 2
    "If `OnItemAdded` is not null, then call it with the `this` and `item` parameters, otherwise do nothing" – stuartd Aug 17 '20 at 11:29
  • Does this answer your question? [what is invoking?](https://stackoverflow.com/questions/6888705/what-is-invoking) – Itsme1 Aug 17 '20 at 11:35
  • I don't get why you think the code is being called again. `this` is a reference to the current instance of the class. – Palle Due Aug 17 '20 at 11:36
  • `OnItemAdded` seems to be an event. It is null if nothing is currently subscribed to this event. `Invoke` will raise the event. The line is (more or less) a shortcut for `if (OnItemAdded != null) OnItemAdded(this, item);` – Klaus Gütter Aug 17 '20 at 11:42
  • `OnItemAdded` is an event (and it has wrong name for event, since `On.. ` name [should be used](https://learn.microsoft.com/en-us/dotnet/standard/design-guidelines/event) for a method rising this event). `event.Invoke` will rise event (call all event handlers what were subscribed). `event?.Invoke` is a thread-safe call with a null check. – Sinatr Aug 17 '20 at 11:43
  • Please show us how `OnItemAdded` is defined. – mjwills Aug 17 '20 at 11:45
  • Great everything is clear now. I follow example in book and I did not come to the part wher event OnItemAdded would be created. Noted for future questions, to finish chapter (or at least check on the end code if this is event) before trying to understand everything. – Bumbar Aug 17 '20 at 12:54

1 Answers1

2

Please see this answer on why the null-check is used. Before c# 6.0, it was good practice to copy the reference to a local variable before invoking. This would help with multi-threading, and subscribers, unsubscribing in between the null-check and the invoke.

There are a couple of reasons for this form:

  • The if evt != null check ensures that we don't try to invoke a null delegate. This can happen if nobody has hooked up an event handler to the event
  • In a multithreaded scenario, since delegates are immutable, once we've obtained a local copy of the delegate into evt, we can safely invoke it after checking for non-null, since nobody can alter it after the if but before the call.
Thomas Luijken
  • 657
  • 5
  • 13