Friday, February 09, 2007

VB.NET Logical Operators are lame

While writing some application architecture documentation for my current project, I drew a blank looking for the technical term "short-circuit" logical operators.

These are really simple in C#.

public bool Method1()

{

   Console.WriteLine("Method1 called.");

   return false;

}

public bool Method2()

{

   Console.WriteLine("Method2 called.");

   return true;

}

public void ShowShortCircuiting()

{

   Console.WriteLine("Regular AND:");

   Console.WriteLine("Result is: {0}", Method1() & Method2());

   Console.WriteLine("Short-Circuit AND:");

   Console.WriteLine("Result is: {0}", Method1() && Method2());

}

Produces the following output:

Regular AND:
Method1 called.
Method2 called.
Result is: False
Short-Circuit AND:
Method1 called.
Result is: False

The concept is really simple too: If the first item isn't true then don't bother executing the next condition.

When speaking with a colleague, he asked if this was possible in VB.NET. Google says yes. But isn't syntax in VB is completely backward??

The C# equivalents map to VB.NET, thusly:

C#: &
VB: And
C#: &&
VB: AndAlso

To quote the article I've highlighted:

If you want the second test to be executed every time, use And. If that's not what you want, use AndAlso.

Syntax-wise, I think that this reads as: "I want this and also this to be evaluated". But if the first condition doesn't pass, (insert smirk) wouldn't it better to say, "I want this, and maybe this to be evaluated."??

I'm not sure what prompted me to switch from VB6 to C#, but boy, I'm glad I did.

2 comments:

Adam said...

A fellow Torontonian and bonified Canuck here. EH!

I'm a veteran programmer coming from the days of C/C++ and I'll add a little light to how C has always provided the && operator...

It's easier to understand the rationale basing on a practical scenario as such...

Take, for example, an object that has a property Name. If you attempt to check the property without evaluating whether or not the object is in fact been instanced (i.e. not nothing), then you will throw exception - yes?

So you write as follows:

If Not MyObject Is Nothing AndAlso MyObject.Name = "hello" Then

Before the AndAlso you would have nest the conditions.

Simple. ;)

Thanks! Good day! Eh!

ps. living is Houston - missing snow ha ha!

bryan said...

Thanks Adam,

btw -- had a good friend living in Arizona refer to their 110F+ summers as our 10F winters -- you just don't go outside. Not having to deal with snow is nice.