Coalesce operator and Conditional operator in VB.NET

28,997

Solution 1

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)

Solution 2

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

Solution 3

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
Share:
28,997
num3ri
Author by

num3ri

Updated on July 09, 2022

Comments

  • num3ri
    num3ri almost 2 years

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

  • awakez144
    awakez144 over 13 years
    *Note: using the if statement that way only applies in VB.NET 2008 and onwards.
  • LosManos
    LosManos over 11 years
    Nope. IIf evaluates all parameters since it is a regular call. See dotnetslackers.com/VB_NET/…
  • miroxlav
    miroxlav about 10 years
    Utilizing LINQ, this is the most effective Coalesce() implementation around.
  • Guillermo Prandi
    Guillermo Prandi over 8 years
    To use the If() function as a coalesce operator, it must be called with just two parameters, and it must be used for reference types: Dim objC = If(objA,objB) This would set objC to objA unless objA is Nothing, in which case objC would be set to objB, whether it is Nothing or not.
  • James Curran
    James Curran over 8 years
    The problem with this (and ivan's below), is that all parameters will be evaluated. So, if I write Dim thingie = Coalesce(Session("thingie"), new Thingie) a new Thingie object will be created every time (although it will be thrown away if a Thingie exist in the Session)
  • brandito
    brandito about 6 years
    For 2006+ support use IIf from memory?
  • jmoreno
    jmoreno almost 6 years
    @Brandito: the IIF function is just that, a function, one that you could write yourself. It does not do coalescence, you would have to write that function yourself. If is a builtin operator, and does do coalescence if you only provide 2 arguments.
  • Brain2000
    Brain2000 over 4 years
    Given that IIf( ) is a function and If( ) is not, the main side effect is that If( ) only evaluates the true/false side, where IIf( ) will evaluate BOTH sides, even if it only returns one of them.