35

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?

Wormbo
  • 4,978
  • 2
  • 21
  • 41
marsh
  • 2,592
  • 5
  • 29
  • 53
  • This is the safe-navigation operator, new in C# 6. There must be a duplicate somewhere on SO. – senshin Dec 15 '15 at 20:08
  • 2
    No, this is not the same thing as declaring a nullable type. What you're seeing is C#6 syntax, called the `null conditional operator` – Jonesopolis Dec 15 '15 at 20:09
  • 1
    Here's the [documentation](https://msdn.microsoft.com/en-us/library/dn986595.aspx) – juharr Dec 15 '15 at 20:10
  • 9
    I'd say this question is not a duplicate at all, as it sort-of has question and top answer reversed. The OP here wanted to know what `?.` does, while the referenced "duplicate" was asked when that particular feature didn't even exist in C# yet. Most search results for question marks also only refer to the conditional oerator, null coalescing operator or nullable struct types, so how are you supposed to figure out it's "conditional access"? Keep in mind that symbol characters are really hard to search for. – Wormbo Dec 15 '15 at 20:29

1 Answers1

48

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();
}
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • 1
    Why response to this, when it is so clearly a dup? – Lynn Crumbling Dec 15 '15 at 20:12
  • 7
    @GrantWinney I'd argue that when someone comes to this question from Google, they'll see the signpost pointing to the other question. Then, they'll read about how there was previously no concise way to do null conditional checks, but now there is... and they're going to have an "ah ha!" moment of sorts. – Lynn Crumbling Dec 15 '15 at 20:21