This would be a very quick post on bitwise and logical operations i.e. & and &&, | and ||. Let’s start it with some coding statement.
static void Main(string[] args)
{
List<int> lst = new List<int>();
lst = null;
if (lst != null & lst.FirstOrDefault() == 2)
{
Console.WriteLine("In Bitwise");
}
if (lst != null && lst.FirstOrDefault() == 2)
{
Console.WriteLine("In Logical");
}
Console.ReadLine();
}
As you can see in the code above. We declared a list of integers, and initializes it to null. Now what we want is this, we need to check if the list is not null and then if it is not, we take out the first entry from it.Now if you are taking out the first item from a list which is null, compiler will throw a null reference exception, as you are referring to a null object. So the statement, lst.FirstOrDefault() will always throw an exception.
Behold the second if condition, where we have used the logical operator &&. Since this is a logical operation, if the value on the left is false, compiler would not even bother to go and figure out what the statement on the right side will return. Whether it is true or false, the overall result would be false.
For the first if condition, we have used the bitwise operator &. What it does basically is compare the operand bit by bit. And in order to compare the two operands, it need to execute both the left and the right condition. Since the execution of lst.FirstOrDefault() will throw an exception, and the code will break.
So, here is the jest. You can use both logical && and bitwise & operators, but using bitwise operator will result in execution of both conditions.The term execution of both conditions may be misleading. So let’s clarify it with an example. Here is the truth table of logical AND operation.
Now let’s say we have following code:
if (Statement1 && Statement2)
{
//Some Condition
}
As it is clear from the table above. If any of the statement is false, the overall result would be false. So, if the Statement1 is false, there is no need to evaluate Statement2 as no matter what it would be, the final result would ultimately be false.
But if the Statement1 is true, there is a need for evaluating the Statement2 as it could either be true, or false. And it depends on Statement2 what would be overall outcome of the condition.
That is to say, logical AND and OR operations would not bother evaluating Statement2 until there is a need. On the contrary, Bitwise AND and OR operations would every time evaluate both conditions.
Happy Reading!!!
0 comments