Reputation: 12386
Is it possible to do one line if statement in VB .NET? If so, how?
Upvotes: 90
Views: 143375
Reputation: 347
Single line
Syntax:
If (condition) Then (do this)
Example:
If flag = true Then i = 1
Multiple ElseIf's
Syntax:
If (condition) Then : (do this)
ElseIf (condition2) Then : (do this)
Else : (do this)
End If
OR
If (condition) Then : (do this) : ElseIf (condition2) Then : (do this) : Else : (do this) : End If
Multiple operations
Syntax:
If (condition) Then : (do this) : (and this) : End If
Upvotes: 20
Reputation: 19
If (condition, condition_is_true, condition_is_false)
It will look like this in longer version:
If (condition_is_true) Then
Else (condition_is_false)
End If
Upvotes: 0
Reputation: 161
Easier than you think, noticed no-one has put what I've got yet, so I'll throw in my 2-cents.
In my testing you don't need the continuation? semi-colon
, you can do without, also you can do it without the End If
.
<C#> = Condition.
<R#> = True Return.
<E> = Else Return.
Single Condition
If <C1> Then <R1> Else <E>
Multiple Conditions
If <C1> Then <R1> Else If <C2> Then <R2> Else <E>
Infinite? Conditions
If <C1> Then <R1> Else If <C2> Then <R2> If <C3> Then <R3> If <C4> Then <R4> Else...
' Just keep adding "If <C> Then <R> Else" to get more
-Not really sure how to format this to make it more readable, so if someone could offer a edit, please do-
Upvotes: 3
Reputation: 17
Its simple to use in VB.NET code
Basic Syntax IIF(Expression as Boolean,True Part as Object,False Part as Object)As Object
Upvotes: 0
Reputation: 8630
Use IF().
It is a short-circuiting ternary operator.
Dim Result = IF(expression,<true return>,<false return>)
SEE ALSO:
Upvotes: 137
Reputation: 15813
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
Upvotes: 17
Reputation: 95432
You can use the IIf function too:
CheckIt = IIf(TestMe > 1000, "Large", "Small")
Upvotes: 1
Reputation: 82325
It's actually pretty simple..
If CONDITION Then ..INSERT CODE HERE..
Upvotes: 25
Reputation: 115701
Just add Then
:
If A = 1 Then A = 2
or:
If A = 1 Then _
A = 2
Upvotes: 4