Difference in calling an event?

Hello!
Very nice course, Thank you so much!

I have a question regarding the events. I know you’ve explained the events available in unity and c#, but I can see that you’re still checking if an event (Action) is not null and then you call it as a method, we can’t instead call it this way => OnQuestionAsked?.Invoke(); instead of if (OnQuestionAsked ! = null) { OnQuestionAsked(); }
Like is there any difference between those two or you’re showing us different ways of calling events?

The null conditional operator (?.) is a new thing introduced in C# 6. Before that we had to manually check if the event is null.

if (myEvent != null)
{
    myEvent();
}

From C# 6 onwards, we could make it shorter using the null conditional operator

myEvent?.Invoke();

It’s essentially the same thing. The operator will immediately return null if the expression on the left-hand side evaluates to null, so it prevents a NullReferenceException. If the left-hand side does not evaluate to null, the . is treated as usual. This does not mean the old way is wrong. It’s perfectly fine and a lot of people still use it that way. It’s a matter of preference.

2 Likes

Okay, Awesome :slight_smile:

Thank you so much!

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms