17

cIn C# there is a null conditional operator ?. (sometimes called the Elvis operator) like so:

var name = project?.customer?.name;

which doesn't fail but instead return null if project or customer is null.

Is there an equivalent in VB.NET?

Note that I am not looking for If(b, x, y) but the very ?. replacement.

8
  • I am surprised I haven't found any answer when searching and nothing in Stack overflow.
    – LosManos
    Commented Aug 2, 2017 at 20:35
  • stackoverflow.com/questions/31730494/…
    – Steve
    Commented Aug 2, 2017 at 20:42
  • 1
    Please type in your C# sample again without typos. It's hard to tell exactly what your question is (I count 2 typos - in addition to the obscure 'Elvis' naming). Commented Aug 2, 2017 at 20:47
  • @DaveDoknjas In fairness, "Elvis operator" was a commonly used name when the operator didn't have an official name yet.
    – user743382
    Commented Aug 2, 2017 at 20:55
  • 1
    @DaveDoknjas Yes, in other languages, "Elvis operator" refers to ?:, but C# never had ?:. When C# gained ?., the same name was used unofficially.
    – user743382
    Commented Aug 2, 2017 at 20:57

1 Answer 1

21

VB also has the null conditional operator (never heard the term 'Elvis' operator):

Dim name = customer?.name

Notes:

  1. Inferred typing in VB requires Option Infer On

  2. I'm pretty sure that your original C# code sample should have been:

    var name = customer?.name;
    
4
  • 1. I believe Option Infer On is set as default. 2. A typo of mine. Thank you for correcting. The syntax is the same in C# and Vbnet. Schtoopid of me.
    – LosManos
    Commented Aug 2, 2017 at 21:40
  • @Enigmativity: Yeah - saw that when I looked it up, but had never heard anyone call it that before today. Commented Aug 3, 2017 at 0:59
  • @DaveDoknjas The term "Elvis operator" was actually used by C# language design team members (I believe it was Mads Torgersen) in the C#6 spotlight video for the null-propagating operator feature. While the wikipedia page specifically mentions the Elvis operator as being ternary conditional, it also has a link to the safe navigation operator in the See Also part. So it's not that it's entirely wrong. Commented Aug 3, 2017 at 9:05
  • Interesting. I didn't know this worked for vb.net too.
    – Rich
    Commented Jan 24, 2024 at 21:50

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.