![]() |
|
|
IIf in VB2005 vs IF in VB2008 - Whats new in VB9.0 |
Post Reply
|
| Author | |
Jijo
Admin Group
Joined: 31 Dec 05 Location: United Kingdom Posts: 495 |
Quote Reply
Topic: IIf in VB2005 vs IF in VB2008 - Whats new in VB9.0Posted: 03 Sep 07 at 9:17am |
|
IIf in VB2005 vs IF in VB2008
IIf in VB2005 cannot be considered as a true tenary operator. Lets first have a look into what it does. IIf(condition,firstValue,secondValue) Here the condition is checked and if true it will return firstValue else will return secondvalue. Dim a As Integer=3 Dim b as Integer=5 Dim c As Integer c=IIf(a>b,a,b) Here condition is false as 3>5 is false. Since condition is false it return 5. Till now things are fine. But if you know that IIf can do more than this you will find whats the problem. For example the second and third value can be a function call. But the only restriction is that it should return something. Consider a case where a school park charge is $10 and twice for those above 16 We can write this as follows Dim baseCharge as Double = 10D Dim age as Integer Dim totCharge as Double age = 14 totCharge = IIf(age<=16,baseCharge,getAdultCharge(baseCharge)) Private Function getAdultCharge(ByVal intVal As Double) As Double MessageBox.Show("Just to check if this is called.", "Check") Return intVal * 2 End Function So as per our value age is 14 so the value returned should be 10. If you chek it there is nothing wrong but you might have seen a messagebox popping up. So thats the problem, there was no need to call that function since the age was just 14 and there was no need to calculate the adult fare. So we can conclude as this. Even if the condition is true or false, part 2 and part 3 are evaluated. But it was good if part 2 is executed only when condition is true, and part 3 only when condition becomes false. It should have save little time, or even can avoid some errors isn't? So for this solution VB2008 came with a true operator IF, everything is the same just that they made it in a way that we required as stated above totCharge = If(age<=16,baseCharge,getAdultCharge(baseCharge)) The above statement will not show the MessageBox as it won't call the function to calculate the adultCharge. But make sure you don't get confused with normal If used in If---Then clause. What is new in VB 2008
What are Extension Method
Partial Methods in C# 3.0 and VB.net 9.0
Nullable Types in VB 2008 & VB 2005
Relaxed Delegates. VB 2008 / VB 9.0
|
|
![]() |
|
Post Reply
|
| Forum Jump | Forum Permissions ![]() You cannot post new topics in this forum You cannot reply to topics in this forum You cannot delete your posts in this forum You cannot edit your posts in this forum You cannot create polls in this forum You cannot vote in polls in this forum |