Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Question Mark syntax on method call [duplicate]

Tags:

c#

What does the ? indicate in the following C# code?

var handler = CallBack; handler?.Invoke(); 

I have read that you can use a ? before a type to indicate that it is a nullable type. Is this doing the same thing?

like image 883
marsh Avatar asked Dec 15 '15 20:12

marsh


People also ask

What does double question mark do?

If double question marks are uses it is to emphasise something in return, usually from the shock of the previous thing said. For example, if I said: 'My dog just died' (sad, but used for example...)

What is the question mark used for in C#?

It's the null conditional operator. It basically means: "Evaluate the first operand; if that's null, stop, with a result of null. Otherwise, evaluate the second operand (as a member access of the first operand)."

What is the use of double question mark in C#?

It is used to define a default value for a nullable item (for both value types and reference types). It prevents the runtime InvalidOperationException exception.

What does the question mark mean in Ruby?

It is a code style convention; it indicates that a method returns a boolean value (true or false) or an object to indicate a true value (or “truthy” value). The question mark is a valid character at the end of a method name. https://docs.ruby-lang.org/en/2.0.0/syntax/methods_rdoc.html#label-Method+Names.


1 Answers

This is C#6 code using the null conditional operator indicating that this code will not throw a NullReferenceException exception if handler is null:

Delegate handler = null; handler?.Invoke(); 

which avoid you writing null checks that you would have to do in previous versions of the C# language:

Delegate handler = null; if (handler != null) {     handler.Invoke(); } 
like image 175
Darin Dimitrov Avatar answered Sep 20 '22 15:09

Darin Dimitrov