VB.NET null coalescing operator?

40,558

Solution 1

Yes, there is, a long as you're using VB 9 or later (included with Visual Studio 2008).

You can use the version of the If operator overloaded to accept only two arguments:

Dim myVar? As Integer = Nothing
Console.WriteLine(If(myVar, 7))

More information can be found here in a blog post by the VB.NET team.

(Yes, this is an operator, even though it looks like a function. It will compile down to the same IL as the "proper" null-coalescing operator in C#.)

Example

Dim b As Boolean?
Console.WriteLine("{0}.", If(b, "this is expected when b is nothing"))
'output: this is expected when b is nothing.

b = False
Console.WriteLine("{0}.", If(b, "this is unexpected when b is false"))
'output: False.

b = True
Console.WriteLine("{0}.", If(b, "this is unexpected when b is true"))
'output: True.

Solution 2

According to this question it would seem the answer is If()

Share:
40,558
RiddlerDev
Author by

RiddlerDev

Principal Consultant and Co-Owner of Milk Can LLC.

Updated on July 15, 2022

Comments

  • RiddlerDev
    RiddlerDev almost 2 years

    Possible Duplicates:
    Coalesce operator and Conditional operator in VB.NET
    Is there a VB.NET equivalent for C#'s ?? operator?

    Is there a built-in VB.NET equivalent to the C# null coalescing operator?

  • Cody Gray
    Cody Gray almost 13 years
    If you find a duplicate question, please flag the question as a duplicate rather than posting an answer that links to the duplicate question. That helps to keep down clutter on the site. Only post an answer if you think you can add value to the question. Thanks!
  • Cody Gray
    Cody Gray almost 13 years
    If you find a duplicate question, please flag the question as a duplicate rather than posting an answer that links to the duplicate question. That helps to keep down clutter on the site. Only post an answer if you think you can add value to the question. Thanks!
  • SeeSharp
    SeeSharp almost 13 years
    Sorry, my bad. Didn't realise; will certainly bear it in mind for the future though.
  • davecoulter
    davecoulter almost 13 years
    @Cody Gray -- thanks, will do next time.
  • Lukazoid
    Lukazoid almost 9 years
    GetValueOrDefault(ByVal default As T) forces evaluation of the default parameter even if it is not required, the null-coalescing operator will only evaluate default if HasValue is false.
  • Crono
    Crono almost 3 years
    It should be noted that as opposed to the C# operator, the VB.NET implementation does not allow for throw expressions. It only accepts value expressions.
  • amonroejj
    amonroejj about 2 years
    Linked blog article on the Wayback Machine: web.archive.org/web/20150716145313/http://blogs.msdn.com/b/…