So I have case statements grouped together here, but I have a few case statements that need extra decision based on a second variable after the original case is confirmed.
This is what I have now:
Case "PRIVATE_PARTY"
If Condition = KBB_CONDITION_EXCELLENT Then
Vehicle.MarketValue = Response.PrivatePartyExcellent
ElseIf Condition = KBB_CONDITION_GOOD Then
Vehicle.MarketValue = Response.PrivatePartyGood
Else
Vehicle.MarketValue = Response.PrivatePartyFair
End If
Is it possible to add an “and” statement to some of the cases like this and have the code work in the same fashion?
Case "TRADE_IN" And Condition = KBB_CONDITION_EXCELLENT
Vehicle.MarketValue = Response.TradeInExcellent
And then just have 3 case statements instead of one but the code wouldn’t look ugly. By the way Condition is declared instead the same select.
- Would this work?
- Is there any reason why I shouldn’t use this if it does work?
Short Answer
The code might compile, but it will be wrong. Don’t try to use
Select Caselike this! I explain why below.Long Answer
Select Casein VB.NET is basically a glorifiedIf/ElseIf/etc. (it is not semantically the same as aswitch). So attempting to write your code this way would actually offer no real benefit over writing the equivalent code usingIf,ElseIf, etc.That said, the below does compile with
Option Strict OffandOption Infer Onusing VB 9.Note: I am not saying this will “work” just because it compiles. The point I am in the process of making here is that just because code compiles, that doesn’t mean it does what you expect. Again: this compiles, but it will not work. Don’t use it.*
The question is: what does it compile to?
Cracking open the code in Reflector, here’s what you see:
So the VB compiler interprets
"Private Party" AndAlso i = 1as aBoolean, which it will then convert to aString(either “True” or “False”) in order to compare it tos.In other words, this isn’t going to work the way you want it to. I’d honestly just go for the
If/ElseIfblock; it would be easier to read (in my opinion).*You probably already understood the point I was making; I just wanted to make it 100% clear 😉