Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Coalesce operator and Conditional operator in VB.NET [duplicate]

Possible Duplicate:
Is there a conditional ternary operator in VB.NET?

Can we use the Coalesce operator(??) and conditional ternary operator(:) in VB.NET as in C#?

like image 949
user42348 Avatar asked Mar 10 '09 05:03

user42348


3 Answers

I think you can get close with using an inline if statement:

//C#
int x = a ? b : c;

'VB.Net
Dim x as Integer = If(a, b, c)
like image 174
Nick Josevski Avatar answered Oct 31 '22 15:10

Nick Josevski


Sub Main()
    Dim x, z As Object
    Dim y As Nullable(Of Integer)
    z = "1243"

    Dim c As Object = Coalesce(x, y, z)
End Sub

Private Function Coalesce(ByVal ParamArray x As Object())
    Return x.First(Function(y) Not IsNothing(y))
End Function
like image 38
Mina Luke Avatar answered Oct 31 '22 16:10

Mina Luke


just for reference, Coalesce operator for String

Private Function Coalesce(ByVal ParamArray Parameters As String()) As String
    For Each Parameter As String In Parameters
        If Not Parameter Is Nothing Then
            Return Parameter
        End If
    Next
    Return Nothing
End Function
like image 42
ivan Avatar answered Oct 31 '22 15:10

ivan