• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 652
  • Last Modified:

difference between conditional and logical operators in c#

Need help with example to explain
difference between conditional and logical operators in c#[ &,&&,|,||)
0
rnsr
Asked:
rnsr
  • 4
  • 3
  • 2
  • +2
4 Solutions
 
käµfm³d 👽Commented:
&  -  Bitwise AND
&& -  Logical AND
|  -  Bitwise OR
|| -  Logical OR

Open in new window


Bitwise operators are used to evaluate bits, hence the name. Logical operators are used on boolean expressions (disregarding bits, since there is no "bit" type). Here are examples of each:

Bitwise AND
bool CheckMyRegexOptions(RegexOptions options)
{
    if ((options & RegexOptions.Compiled) == RegexOptions.Compiled)
    {
        // options was assigned the bit flag "Compiled"
        
        // Here, even though it looks like we're doing logical AND,
        //  we're not. The comparison for the "if" is between
        //  (options & RegexOptions.Compiled) and RegexOptions.Compiled
        //  The bitwise AND evaluates the bit position that Compiled is
        //  associated with. An AND returns 1 (for that position) if the
        //  flag is set, or 0 if the flag is not set.
    }
}

Open in new window



Logical AND
bool iHaveMoney = true;
bool iHaveARide = true;

if (iHaveMoney && iHaveARide)
{
    // Both are true, so I am going to the movies. Hooray!
}
else
{
    // One or both were false, so I am staying home. Boo.
}

Open in new window



Bitwise OR
RegexOptions options = RegexOptions.Compiled | RegexOptions.IgnoreCase;
// This sets "options" to be both "Compiled" and "IgnoreCase". OR sets; AND queries

Open in new window


Logical AND
bool iHaveMoney = true;
bool iHaveAFriendWithMoney = true;

if (iHaveMoney && iHaveAFriendWithMoney)
{
    // Either are true, so I can buy that new CD
}
else
{
    // Both were false, so I going to have to read a book instead.
}

Open in new window

0
 
Dave BaldwinFixer of ProblemsCommented:
The operators you show above are just logical.  This page from Microsoft describes the C# operators very well: http://msdn.microsoft.com/en-us/library/6a71f45d%28v=vs.71%29.aspx  You can click on each one and get a full page to describe it.
0
 
käµfm³d 👽Commented:
To expand upon the concept of "bitwise," think of all numbers as a string of bits (because in truth, they are). If you have the number 4 and you store it in an int variable, you have 32 bits to represent the number 4. These bits are the binary representation of the number. This is what 4 looks like in binary:

    0000 0000 0000 0000 0000 0000 0000 0100

There are, of course, no spaces in between these values--I added them for visual effect.

Now each of these positions can be either of two values: 1 (on) or 0 (off). If we have some series of related concepts that can either be on or off, then we can exploit this binary feature of our int variable to pack more data into the variable than just a simple number. This is the concept of bit flags. Each bit serves to indicate whether or not some value is on or off.

In my above example, lets say that the right-most index represents the "Compiled" flag, and the 2nd right-most represents the "IgnoreCase" flag. If both were on (and assuming nothing else was), then our int would look like this:

    0000 0000 0000 0000 0000 0000 0000 0011

As mentioned previously, we would use a bitwise OR to set these values (as demonstrated above). If we wanted to know whether or not these values had been set, then we would use a bitwise AND.
0
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

 
systanCommented:
in pascal;
if ( (a=1) AND (b=2) )
if ( (a=1) OR (b=2) )

in c_sharp;
if ( (a==1) && (b==2) )
if ( (a==1) ||  (b==2) )


http://msdn.microsoft.com/en-us/library/6a71f45d%28v=vs.71%29.aspx
http://www.blackwasp.co.uk/CSharpLogicalOpOverload.aspx
0
 
käµfm³d 👽Commented:
I must be sleepy  : )

My last example above, "Bitwise AND" should have been "Bitwise OR" and the example code was incorrect as well. It is corrected below.

Bitwise OR
bool iHaveMoney = true;
bool iHaveAFriendWithMoney = true;

if (iHaveMoney || iHaveAFriendWithMoney)
{
    // Either are true, so I can buy that new CD
}
else
{
    // Both were false, so I going to have to read a book instead.
}

Open in new window

0
 
rnsrAuthor Commented:
Bitwise represent ON and Off concept. But programatically where can i use it in project.
0
 
Dave BaldwinFixer of ProblemsCommented:
Bitwise is used where the bits in a variable mean something like uppercase/lowercase or 'flags' for processes.  You can use "char & 0x5f" to make a character uppercase (at least in ASCII).  On this page http://msdn.microsoft.com/en-us/library/ms684863%28v=vs.85%29.aspx is an example of "Process Creation Flags" for Windows.  The constants names are usually used instead of the hex values.  To set the flags, you would normally use 'or' like "flagset | CREATE_BREAKAWAY_FROM_JOB" to include '0x01000000' in the value of 'flagset'.
0
 
käµfm³d 👽Commented:
Bitwise represent ON and Off concept. But programatically where can i use it in project.
That depends on your design. I gave you examples on how they work.

The Regex class has a Match method that takes an optional parameter specifying "options". These options are specified as a bit flag. Two or more options can be set by bitwise ORing them together. This sets the individual positions "on" in the value. This is, of course, not the only example of built-in bit flags in .NET; however, I can't readily think of some of the others.

As far as your code, the easiest way to create a bit flag is to make an enumeration (example following). Be sure to set the values of the enumeration to powers of 2 otherwise the flags won't work (each bit position in binary is a power of 2). Let's take a simple example and say you want a function to check a number for certain optional conditions. Let's define these conditions as:

Number must be positive
Number must be a power or 3
Number must not be zero

Now none, any, or all of these conditions can be checked by your function. You *could* define your function with a series of boolean parameters:

bool VerifyNumber(int value, bool isPositive, bool isPower3, bool isGreaterThan0) { }

Open in new window


which would be fine. But you *could* also create a bit flag for this. Let's define the flag as:

[Flags()]
public enum CheckNumberOptions
{
    None = 0,
    IsPositive = 2,
    IsPower3 = 4,
    IsGreaterThan0 = 8,
}

Open in new window


Notice we have a "None" option, which should be zero so we can indicate that no flags are set, and that each value is some power of 2. Bit flags will only work if each value is a power of 2. Also notice the "Flags" attribute. In reality, it doesn't do anything, but MS recommends tagging you bit flag enums with it, so they command, I obey  ; )

To continue, you could then modify the previous function definition to accept a CheckNumberOptions bit flag parameter instead of the booleans:

bool VerifyNumber(int value, CheckNumberOptions options) { }

Open in new window


You would set, using bitwise OR, and pass the options in this manner:

CheckNumberOptions options = CheckNumberOptions.IsPositive | CheckNumberOptions.IsGreaterThan0;

VerifyNumber(4, options);

Open in new window


Inside of your function, you would determine whether or not the values were set by using bitwise AND:

bool VerifyNumber(int value, CheckNumberOptions options)
{
    if (options & CheckNumberOptions.IsPositive > 0)
    {
        if (value < 0) return false;
    }

    if (options & CheckNumberOptions.IsPower3 > 0)
    {
        if (value % 3 > 0) return false;
    }

    if (options & CheckNumberOptions.IsGreaterThan0 > 0)
    {
        if (value <= 0) return false;
    }

    return true;
}

Open in new window


For comparison against a single flag, checking that the result is greater than zero is sufficient. However, if your comparison is against two or more flags, then you have to check the result against the flag you are interested in:

bool VerifyNumber(int value, CheckNumberOptions options)
{
    CheckNumberOptions toCheck = CheckNumberOptions.IsPositive | CheckNumberOptions.IsPower3;
    
    if ((options & toCheck) == CheckNumberOptions.IsPositive)
    {
        if (value < 0) return false;
    }

    if ((options & toCheck) == CheckNumberOptions.IsPower3)
    {
        if (value % 3 > 0) return false;
    }

    return true;
}

Open in new window


Here is an demonstration of what is happening in the checks above.

Comparison Against a Single Flag
0000 1010  -  IsPositive | IsGreaterThan0 (options)
0000 0010  -  IsPositive (check)
---------
0000 0010  -  After bitwise AND, the value (overall) is greater than zero, so the flag was set

Open in new window



Comparison Against Multiple Flags
0000 1010  -  IsPositive | IsGreaterThan0 (options)
0000 0110  -  IsPositive | IsPower3 (check)
---------
0000 0010  -  After bitwise AND

   NOW, if you simply compare greater than zero, this would indicate
   that both flags are set. This is an error. You must check each
   flag in the "check" value separately.


Are They Equal?

0000 0010  -  After bitwise AND
0000 0010  -  IsPositive
---------
true

0000 0010  -  After bitwise AND
0000 0100  -  IsPower3
---------
false

Open in new window

0
 
MajorBigDealCommented:
You could use bitwise AND to check to see if an int is odd or even. if ((num & 1) == 1)  will only be true if the last bit is a 1 which would make it an odd number.
0
 
rnsrAuthor Commented:
i need some time to see it as i am busy for the past one week.
will respond soon.
Thanks,
0
 
rnsrAuthor Commented:
Nice expalined with example
0

Featured Post

[Webinar On Demand] Database Backup and Recovery

Does your company store data on premises, off site, in the cloud, or a combination of these? If you answered “yes”, you need a data backup recovery plan that fits each and every platform. Watch now as as Percona teaches us how to build agile data backup recovery plan.

  • 4
  • 3
  • 2
  • +2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now