Developers Heaven Forum
News: Free Image Hosting:
http://image-host.developers-heaven.net
Share your images free!!!
 
*
Welcome, Guest. Please login or register.
Did you miss your activation email?
March 19, 2010, 08:01:06 PM


Login with username, password and session length


Pages: [1]   Go Down
  Print  
Author Topic: What is difference between “&& ” , “& ”,"||" and "|" operators in C#?  (Read 302 times)
0 Members and 1 Guest are viewing this topic.
admin
Administrator
Full Member
*****
Online Online

Posts: 206


OS:
unknown
Browser:
unknown


View Profile
« on: October 26, 2008, 05:29:43 PM »

What is difference between “&& ” , “& ”,"||" and "|" operators in C#?
1 - In the conditional statements:

When using the && operator the compilier uses short circuit logic, e.g.
it the first condition is false, the second one is not evaluated.
but when using the & operator the compilier evaluate both conditions even the first condition is false.

just like the & and && operator, the double Operator || is a "short-circuit" operator
For example:

if(condition1 || condition 2 || condition 3)If condition1 is true, condition 2 and 3 will NOT be checked.

if(condition1 | condition 2 | condition 3)This will check conditions 2 and 3, even if 1 is already true. As your conditions can be quite expensive functions, you can get a good performance boost by using them.

There is one big caveat, NullReferences or similar problems. For example:

if(class != null && class.someVar < 20)If class is null, the if-statement will stop after "class != null" is false. If you only use &, it will try to check class.someVar and you get a nice NullReferenceException. With the Or-Operator that may not be that much of a trap as it's unlikely that you trigger something bad, but it's something to keep in mind.

2- There is a Second use of the | and & operator though: Bitwise Operations.

 | is the bitwise OR operator. Its used to operate on two numbers. You look at each bit of each number individually and, if one of the bits is 1 in at least one of the numbers, then the resulting bit will be 1 also. Here are a few examples:

A = 01010101
B = 10101010
A | B = 11111111
A & B = 00000000
A = 00000001
B = 00010000
A | B = 00010001
A & B = 00000000
A = 10001011
B = 00101100
A | B = 10101111
A & B = 00001000

Hopefully that makes sense.

« Last Edit: October 26, 2008, 05:41:25 PM by admin » Logged
Pages: [1]   Go Up
  Print  
 
Jump to:  

Google
   
Powered by MySQL Powered by PHP Powered by SMF 1.1.4 | SMF © 2006-2007, Simple Machines LLC

Copyright © Developers-Heaven.net 2008. All rights reserved.
Valid XHTML 1.0! Valid CSS! Dilber MC Theme by HarzeM