Wednesday, December 08, 2004

If Condition statement (VB.Net)

Recently ran into a bug where it seemed that the if statement was not working properly, turns out it was written "wrongly"

The problematic statement was this :If (FunctionA() AndAlso FunctionB()) Then 'Do somethingEndIf

Whereas, it should be written as such :If (FucntionA() And FunctionB()) Then 'Do SomethingEndIf

The difference is this :The latter stops the processing if the first function i.e FunctionA() returns False, which implies that function (FunctionB()) is never evaluated.It may seem the right logic, but if there is some processing that is to be done is FunctionB() - it will not take place, which in some cases may not be right.When we use the And keyword, it makes sure that both FunctionA() and FunctionB() are evaluated before it exits the If statement (assuming no exception is thrown), but for the keyword AndAlso, it exits the If statement as soon as FunctionA() returns false.Just for the record.. ; )