Null-Conditional Operator and Delegates

C# 6.0 Features Series

When you want to invoke an delegate , you might want to perform null check so that you wont get the null reference exception .

In C# 6.0 , we can use the Null-Conditional operator when invoking the delegate to perform the null check and do the invocation . The only catch is that , you cannot do the straightforward way of calling a delegate when followed by the ?. operator . You will need to use the Invoke method as shown below.

FirstNameChanged?.Invoke(this,args)

It is also said to be one of the easiest and the thread safe way to check for nulls before triggering an event.

    1 Comment

Leave A Reply

Your email address will not be published. Required fields are marked *

You May Also Like

C# Compiler Error CS0442 – ‘Property’: abstract properties cannot have private accessors Reason for the Error You’ll get this error...
This is a really simple one . Below is a simple example of an enum called “Designation” defined with the...
This blog post explain the usage of the Checked Block in .NET and how you can use them in Visual...