Bumbar
Bumbar

Reputation: 5

C# what does invoke(this, ,) do?

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?

Upvotes: 0

Views: 1667

Answers (1)

Thomas Luijken
Thomas Luijken

Reputation: 645

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.

Upvotes: 2

Related Questions