Pages

Wednesday, January 16, 2008

AndAlso & OrElse Operators in C#

AndAlso(&&)

The logical operator && is the AndAlso in C#. This is used to connect two logical conditions checking like if ( && ). In this situation both conditions want to be true for passing the logic. Looking at the e.g. below

int a = 100;
int b = 0;
if (b > 0 && a/b <100)

{
Console.Write("ok");
}

The point here is, the condition "b > 0" will check first. Because "b > 0" a false condition, second condition "a/b <100" won't need to check and our "&&" operator won't perform the second condition checking. So actually our execution time is saving in a logical operation in which more conditions are combined using "&&" operator.

And(&)

The difference of "&" operator compared to above is mentioned below

int a = 100;
int b = 0;
if (b > 0 & a/b <100)
{
Console.Write("ok");
}

The point here is, the condition "b > 0" will check first. Because "b > 0" a false condition, second condition "a/b <100" won't need to check. But our "&" operator will perform the second condition checking also. So actually our execution time is losing for a useless checking. Also executing the "a/b <100" unless b>0 is generating an error also.

Or(|) and OrElse(||)

The difference of Or ("|") and OrElse ("||") are also similar to "And" operators, as first one will check all conditions and second one won't execute remaining logical checking, if it's found any of the previous checking is true and saving time. You can analysis these by the below code.

//Or

if (b > 0 | a/b <100)
{
Console.Write("ok");
}

//OrElse
if (b >= 0 || a/b <100)
{
Console.Write("ok");
}

No comments: