VB.NET null coalescing operator?

vb.netNull Coalescing-Operator

vb.net Problem Overview


> 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?

vb.net Solutions


Solution 1 - vb.net

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 - vb.net

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

Solution 3 - vb.net

No. Use GetValueOrDefault; that's why it's there!

Solution 4 - vb.net

I don't believe that there is a built in VB.Net equivalent, but here's an answer: https://stackoverflow.com/questions/4594446/null-coalesce-operator-in-vb-net8

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRiddlerDevView Question on Stackoverflow
Solution 1 - vb.netCody GrayView Answer on Stackoverflow
Solution 2 - vb.netSeeSharpView Answer on Stackoverflow
Solution 3 - vb.netuser541686View Answer on Stackoverflow
Solution 4 - vb.netdavecoulterView Answer on Stackoverflow