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?
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...)
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)."
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.
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.
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(); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With