tags:

views:

60

answers:

5

Hello,

is there any possibility to assign a value to a variable inside an IF condition in VB.NET?

Something like that:

Dim customer As Customer = Nothing

If IsNothing(customer = GetCustomer(id)) Then
    Return False
End If

Thank you

+3  A: 

No, I'm fairly sure this is not possible - but be thankful!

This is a "feature" of C-based languages that I would never encourage the use of, because it is probably misused or misinterpreted more often than not.

I think the best approach is to try and express "one thought per line", and resist coding that combines two operations in the same line. Combining an assignment and a comparison in this way usually doesn't achieve much other than making the code more difficult to understand.

MrUpsideDown
+1  A: 

VB doesn't do that very well, especially since assignment and comparison both use the = operator. It'd get really confusing. And since VB to some degree is designed to be newbie-friendly (The B in "BASIC" actually stands for "Beginner's"), expressions with multiple side effects are not something the language generally likes to do.

If it's essential that you be able to do it all in one line, then you could make the GetCustomer method assign to a ByRef parameter, and return a boolean saying whether the assigned value was null. But really, it's better to just assign and then compare to null.

cHao
Thank you, so I just assign and compare :)
Torben H.
+2  A: 

Sorry, no. On the other hand, it would get really confusing, since VB.NET uses the same operator for both assignment and equality.

If a = b Then 'wait, is this an assignment or comparison?!

Instead, just set the variable and compare:

Dim customer As Customer = Nothing

customer = GetCustomer(id)

If IsNothing(customer) Then
    Return False
End If
Mike Caron
Okay, then I use this way :)
Torben H.
A: 

Thinking out loud because you didn't show Customer or GetCustomer...

        Dim myCust As New Customer
        If myCust.GetCustomer(someID) Then

        End If

Class Customer

    Private _customerID As Integer
    Const noCustomer As Integer = -1

    Public Sub New()
        Me._customerID = noCustomer 'no customer
    End Sub

    Public Function GetCustomer(ByVal id As Integer) As Boolean
        'perform required action to get customer
        'if successful then set Me._customerID to ID else set it to no customer value
        Return Me.HaveCustomer
    End Function

    Public Function HaveCustomer() As Boolean
        If Me._customerID = noCustomer Then Return False Else Return True
    End Function
End Class
dbasnett
A: 

There is no builtin support for doing this, but you could use this workaround.

Public Function Assign(Of T)(ByRef destination As T, ByVal value As T) As T
  destination = value
  Return destination
End Function

And then it could be used like this.

Dim customer As Customer = Nothing 

If IsNothing(Assign(customer, GetCustomer(id))) Then 
    Return False 
End If 
Brian Gideon