Cyberiafreak

"Fortunate are those who take the first steps.” ― Paulo Coelho

Diff between & and && , | and ||

Hi all..

Today I had a confusion in using conditional operator. Normally I used to use ‘&&’ or ‘||’ for checking boolean condition. But when I was going through sample…I stumble to see & everwhere…but functionality wise both are ok.

Then what is the diff between these two operators ( & and && ) , (| and || )..

//EXAMPLE

private void Form1_Load(object sender, EventArgs e)

{

          int val2=10,val3=20;

          bool val1 = false;

         val1 = (val2 != 0) && (val3 / val2 > 2); // always use && ——- case (i)

         val1 = (val2 != 0) & (val3 / val2 > 2); // dont use & ————case (ii)

}

case(i) If the value of the first operand of the && operator is false, then there is no need to consider the value of the second operand because the result will be false regardless. Similarly, the || operator will return true if its first operand is true, regardless of the value of the second operand.

case

(ii) In these, both operands will always be evaluated.  

 

In conditional evaluation of operands, you will see a small performance increase if you use && and || instead of & and |.  As a rule of thumb, always use && and || where possible.

 

Happy validating..

Mahes

Advertisements

May 12, 2006 - Posted by | .NET General

No comments yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s