views:

2038

answers:

4

Is there a VB.NET equivalent for C#'s ?? operator?

+10  A: 

If()

Firas Assaad
IF is the coalesce operator in VB
Nick
+1, I didn't know this! (OTOH, I've been trying to leave VB.NET behind me ... )
John Rudy
+9  A: 

IF() operator should do the trick for you

value = If(nullable, defaultValueIfNull)

http://visualstudiomagazine.com/listings/list.aspx?id=252

Nick
A: 

You can use an extension method. This one works like SQL Coalesce, and is probably overkill for what you are trying to test, but works.

    ''' <summary>
    ''' Returns the first non-null T based on a collection of the root object and the args.
    ''' </summary>
    ''' <param name="obj"></param>
    ''' <param name="args"></param>
    ''' <returns></returns>
    ''' <remarks>Usage
    ''' Dim val as String = "MyVal"
    ''' Dim result as String = val.Coalesce(String.Empty)
    ''' *** returns "MyVal"
    ''' 
    ''' val = Nothing
    ''' result = val.Coalesce(String.Empty, "MyVal", "YourVal")
    ''' *** returns String.Empty
    ''' 
    ''' </remarks>
    <System.Runtime.CompilerServices.Extension()> _
    Public Function Coalesce(Of T)(ByVal obj As T, ByVal ParamArray args() As T) As T

        If obj IsNot Nothing Then
            Return obj
        End If

        Dim arg As T
        For Each arg In args
            If arg IsNot Nothing Then
                Return arg
            End If
        Next

        Return Nothing

    End Function
StingyJack
Downvote and no comments...
StingyJack
Because the language has a built in operator. No reason to even look at extension methods.
Nick
I'm not going to repeat someone else's answer. I figured that it may be nice to provide an alternate solution if you need to check multiple values with a single statement. Since its not a WRONG answer, then should it be downvoted?
StingyJack
Voting isn't strictly tied to "right" or "wrong", but to "helpful" or "not helpful". It's possible to have a correct solution that people find not-helpful, but some other people may find it helpful and vote you back up.
Andrew Coleson
I know. Its just irritating. There should be some comment required when downvoting an item that is not helpful or correct.
StingyJack
-1 for StingyJack's whining. :)
TheSoftwareJedi
Thank You. Where is my Wahhhh-mbulance????
StingyJack
A: 

I'm wondering if the OP isn't looking for IIF instead of if()...

IIF is specified as:

iif({condition}, {true result}, {false result})

This would seem to better emulate what the ? operator in C# does.

Richard B
He asked about the "??" operator, not the "?" operator.
TheSoftwareJedi
I do apologize. I guess you learn something new every day (never knew that there was an ?? operator that worked the same as a simple If statement)Good to know.
Richard B