C # 6 null conditional operator - how toggler code?

I already know that the null-conditional operator can be used to check for a null value before accessing a member.

eg:

 int? length = customers?.Length; // null if customers is null 
 Customer first = customers?[0];

If customersit is null in customers?.Length, it customers?.Lengthwill return null and what nullwill be in the variableint? length = ...

I also know that this can be used for a single atomic operation of a method call in a multi-threaded environment:

public void OnFoo()
{
    Foo?.Invoke(this, EventArgs.Empty);
}

But

AFAIU - if Foo null, then

 Foo?.Invoke(this, EventArgs.Empty);

Also have null

So we are staying with

public void OnFoo()
{
    null; //compilation error
}

And so I ask:

Question

it seems that an operator with a null condition is not only for checking a null value, but if there is one, it moves deeper: x?.y?.c?.d-

but it also acts as a code switch:

Like this:

  public void OnFoo()
    {
        Foo?.Invoke(this, EventArgs.Empty); //Let assume Foo =null;
    }

Is becoming

  public void OnFoo()
    {

    }

? .

+4
1

- , - .

Foo?.Invoke(this, EventArgs.Empty), null, , , , " ", .

Foo?.Invoke(this, EventArgs.Empty)

, Invoke void. :

// Invalid
var result = Foo?.Invoke(this, EventArgs.Empty);

, 7.6.5 # 5:

:

  • invocation , void, . , , - (§8.6) - (§7.15). .
  • , .

, , . invocation , ., , , NULL.

, # 6 , , - , . ( , # 6. , MS, . ECMA # 5, # 6.)

+6

Source: https://habr.com/ru/post/1652014/


All Articles