I have the following class:
public class MyClass
{
public Action SomeAction { get; set; }
}
Before c#-6.0 when calling SomeAction
because it has the potential to be null
we would do something like:
var action = SomeAction;
if (action != null)
{
action();
}
However, in c#-6.0 we now have the null conditional operator and so can write the above as:
SomeAction?.Invoke();
However I find this slightly less readable because of the Invoke
call. Is there anyway to use the null conditional operator in this circumstance without the Invoke
call? Something like:
SomeAction?();
No, there is no such syntax in C# 6.0 or 7.0. The null conditional operator comes in two flavors:
?.
, which you already rejected as too verbose?[
, which doesn't make sense for delegates (and can't be added as an extension, or anything like that)The documentation even directly mentions this:
You need to explicitly call the
Invoke
method because there is no null-conditional delegate invocation syntaxPropertyChanged?(e)
. There were too many ambiguous parsing situations to allow it.
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