Very (very) often we need to write stuff like
Dim Data = GetSomeData()
If Data IsNot Nothing Then
Data.DoSomething()
Else
...
End If
Maybe I am asking in vain but I am seriously hoping that VB.Net has some construct like:
IfExists Data = GetSomeData() Then
Data.DoSomething()
Else
...
End IfExists
In my dreams it does two important things:
Is there anything similar to that that I haven't found yet?
Thanks!
EDIT: Inspired by Bjørn-Roger Kringsjå's Answer I came up with something that would satisfy me (humbled by VB.Net's deficiencies):
<Extension()>
Public Sub IfExists(Of T)(This As T, DoIfNotNothing As Action(Of T), Optional DoIfNothing As Action = Nothing)
If This IsNot Nothing Then
DoIfNotNothing(This)
ElseIf DoIfNothing IsNot Nothing Then
DoIfNothing()
End If
End Sub
Then I can call it like this (with the false part being optional)
GetSomeData().IfExists(Sub(Data) Data.DoSomething())
or
GetSomeData().IfExists(Sub(Data) Data.DoSomething(), Sub() DoSomethingElse())
A variable is considered empty if it does not exist or if its value equals false .
He says that it's also possible to declare a variable without giving it an initial value and also that we must be careful not to use a variable which has been declared without an initial value and that has not been assigned a value.
In Python, sometimes it makes sense to declare a variable and not assign a value. To declare a variable without a value in Python, use the value “None”.
As stated by others and implied by me, it can't be done. Just like to share a 3'rd
solution. This time we're going to use delegates.
Implementation
Public Module Extensions
Public Sub IfExists(Of T)(testExpr As T, trueDlg As Action(Of T), falseDlg As Action)
If (Not testExpr Is Nothing) Then
trueDlg.DynamicInvoke(New Object(0) {testExpr})
Else
falseDlg.DynamicInvoke(New Object(-1) {})
End If
End Sub
End Module
Usage
IfExists(GetSomeData(),
Sub(A As Object)
'We have something (A)
End Sub,
Sub()
'We have nothing
End Sub
)
Shorter:
IfExists(GetSomeData(), Sub(A As Object)
'We have something (A)
End Sub, Sub()
'We have nothing
End Sub)
Or, the shortest version:
IfExists(GetSomeData(), Sub(A As Object) Debug.WriteLine(A.ToString()), Sub() Debug.WriteLine("Nothing"))
No, unfortunately there is nothing like that currently in VB.NET. The closest thing you could do to approximate that behavior would be to write a function like this:
Public Function Assign(ByRef target As Object, value As Object) As Boolean
target = value
Return (target IsNot Nothing)
End Function
Then you could use it like this:
Dim A As SomeType
If Assign(A, GetSomeData()) Then
' ...
Else
' ...
End If
But, as you pointed out, that doesn't really solve either of your stated problems. It's still an extra line of code, and the variable is still not scoped to only be accessible within the block where it was properly assigned.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With