Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using the null conditional operator and actions

Tags:

c#

c#-6.0

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?();
like image 506
TheLethalCoder Avatar asked Dec 23 '22 19:12

TheLethalCoder


1 Answers

No, there is no such syntax in C# 6.0 or 7.0. The null conditional operator comes in two flavors:

  • null-condition member access ?., which you already rejected as too verbose
  • null-condition index ?[, 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 syntax PropertyChanged?(e). There were too many ambiguous parsing situations to allow it.

like image 126
svick Avatar answered Dec 28 '22 05:12

svick