tags:

views:

1591

answers:

7

Is it possible to do one line if statement in VB .NET? If so, how?

A: 

Just add Then:

If A = 1 Then A = 2

or:

If A = 1 Then _
    A = 2
Anton Gogolev
+3  A: 

It's actually pretty simple..

If CONDITION Then ..INSERT CODE HERE..
Quintin Robinson
And the Else part?
codeape
You just put Else <some more code here> at the end.
Joey
+1  A: 

Or

IIf(CONDITION, TRUE_ACTION, FALSE_ACTION)
Dmitry
And this is an expression, while the question asked for a statement. ;-)
peSHIr
+1  A: 

You can use the IIf function too:

CheckIt = IIf(TestMe > 1000, "Large", "Small")
Jon Limjap
+2  A: 

Be careful with the IIf opertor though - it is not always short-circuited and both the true and false expressions are evaluated.

Paul Alexander
+1  A: 

At the risk of causing some cringing by purests and c# programmers, you can use multiple statements and else in a one-line if statement in VB. In this example, y ends up 3 and not 7.

i = 1
If i = 1 Then x = 3 : y = 3 Else x = 7 : y = 7
xpda
Why go half way??? i = 1 : if i = 1 Then x = 3 : y = 3 Else x = 7 : y = 7
hamlin11