Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VB.NET: Assign value to variable inside an IF condition?

Tags:

vb.net

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

like image 400
Torben Avatar asked Jul 28 '10 06:07

Torben


People also ask

Can we assign value in if condition?

Yes, you can assign the value of variable inside if.

How do you assign an IF condition?

Can we put assignment operator in if condition? Yes you can put assignment operator (=) inside if conditional statement(C/C++) and its boolean type will be always evaluated to true since it will generate side effect to variables inside in it.


2 Answers

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
like image 70
Mike Caron Avatar answered Sep 29 '22 20:09

Mike Caron


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.

like image 39
MrUpsideDown Avatar answered Sep 29 '22 20:09

MrUpsideDown