Is there a VB.NET equivalent for C#'s ?? operator?
IF is the coalesce operator in VB
Nick
2008-12-31 16:53:47
+1, I didn't know this! (OTOH, I've been trying to leave VB.NET behind me ... )
John Rudy
2008-12-31 17:03:19
+9
A:
IF() operator should do the trick for you
value = If(nullable, defaultValueIfNull)
Nick
2008-12-31 16:53:06
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
2008-12-31 16:55:24
Because the language has a built in operator. No reason to even look at extension methods.
Nick
2008-12-31 16:59:42
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
2008-12-31 17:08:58
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
2008-12-31 17:11:53
I know. Its just irritating. There should be some comment required when downvoting an item that is not helpful or correct.
StingyJack
2008-12-31 17:13:27
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
2009-01-01 05:55:33
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
2009-01-01 06:12:56