34

I have had a code snippet comes to modify. In there i found this such syntax.

Session("LightBoxID")?.ToString()

I didn't understand what is that Question mark (?) there means. No googling helped me about any hint

Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179
Sandeep Thomas
  • 4,303
  • 14
  • 61
  • 132
  • 1
    Shorthand null check. – Forklift Mar 28 '17 at 16:10
  • 7
    @AlexeiLevenkov this question is not related to nullable types. Please be careful when closing questions – Sergey Berezovskiy Mar 28 '17 at 16:13
  • 1
    Null-conditional operator a.k.a. safe navigation operator a.k.a. the Elvis operator. https://msdn.microsoft.com/en-us/library/dn986595.aspx – Dennis_E Mar 28 '17 at 16:14
  • 1
    This *is* a duplicate but it's not about nullable types at all. It's about the [Null Conditional operator](https://msdn.microsoft.com/en-us/library/dn986595.aspx) – Panagiotis Kanavos Mar 28 '17 at 16:15
  • Also you can check this question http://stackoverflow.com/questions/41524749/c-sharp-null-conditional-operator – Sergey Berezovskiy Mar 28 '17 at 16:16
  • I've created summary answer - http://stackoverflow.com/questions/43075113/what-question-mark-means-in-c-sharp-code hopefully it will start showing up in searches at some point... – Alexei Levenkov Mar 28 '17 at 16:46
  • Possible duplicate of [What question mark means in C# code](http://stackoverflow.com/questions/43075113/what-question-mark-means-in-c-sharp-code) –  Apr 24 '17 at 19:32

2 Answers2

41

It's the Null-Conditional Operator It's a syntactic sugar for null checking:

return str?.ToString();

will become

if (str == null)
{
    return null;
}
return str.ToString();
Ofir Winegarten
  • 9,215
  • 2
  • 21
  • 27
34

It performs a null-check on Session("LightBoxID") before attempting to call .ToString() on it.

MS Docs: Null-conditional operators ?. and ?[]

trashr0x
  • 6,457
  • 2
  • 29
  • 39