Martin Verjans Martin Verjans - 22 days ago 9
Vb.net Question

Nested inline if statement

In VB .Net it is possible to use inline

If
statements, like this

if a Then ret = "A" Else ret = "Not A"


I know it is also possible to nest these statements. I know this might not be good practice as readability drops down...

If a Then If b Then ret = "A & B" Else ret = "A & Not B" Else ret = "Not A"


which will be evaluated like this :

If a Then
If b Then
ret = "A & B"
Else
ret = "A & Not B"
End If
Else
ret = "Not A"
End If


Now if I remove the last
Else
statement, I get this :

If a Then If b Then ret = "A & B" Else ret = "A & Not B"


which is :

If a Then
If b Then
ret = "A & B"
Else
ret = "A & Not B"
End If
End If


So I guess the compiler finds the
Else
and matches it to the last openend
If
in the line, which makes sense.
My question is : Is it possible to change the evaluation order ? By that I mean is it possible that the Else is matched with the first if ?

So it would look like this :

If a Then
If b Then
ret = "A & B"
End If
Else
ret = "Not A"
End If


But inlined (something like this, parenthesis added to understand what I mean) :

If a Then ( If b Then ret = "A & B" ) Else ret = "Not A"


I tried with parenthesis or adding a
End If
but it provokes syntax errors, and I couldn't find documentation for this.

I'm not stuck anywhere and I know this might not be a good prorgamming practice, but I just wanted to know (out of curiosity) if it was possible.

I know also I could switch the statements (i.e. test b before a), but let's say I can't (a is a List and must be tested for Nothing before b which would be the Count for example).

Answer

You could do it like this

ret = If(a, If(b, "A & B", "A & Not B"), "Not A")

Personally, I never understood the need to put everything in one line.

Comments