Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the purpose of "?" in (someDelegateName)?.Invoke();? [duplicate]

The following code snippet was highlighted in Visual Studio alongside a suggestion for simplifying it.

if ( drawMethodsDelegate != null )
    drawMethodsDelegate ( e.Graphics );

When I clicked on the lightbulb suggestion thing, Visual Studio refactored it into the following

drawMethodsDelegate?.Invoke ( e.Graphics );

And no. The question mark is not a typo. I don't understand what the question mark is used for and I can't find anything relevant on MSDN. I also looked at the Tutorial Point Delegates page but found no useful information.

Tutorial Point page , MSDN Delegates page , MSDN Control.Invoke page

like image 788
James Yeoman Avatar asked Mar 05 '17 11:03

James Yeoman


1 Answers

This is the null conditional operator.

drawMethodsDelegate?.Invoke ( e.Graphics );

Provided that drawMethodsDelegate is not null calls the Invoke method. It is an operator that being introduced in the 6th version of C# and you can see it as a syntactic sugar, which helps you to write less code for handling null checks.

Last but not least, the above check is also thread-safe !

For further info please have a look here

like image 133
Christos Avatar answered Oct 13 '22 09:10

Christos