Wednesday, December 19, 2012

C# and .NET interview question: -What is short circuiting in C#?




When developers get this .NET interview question many of them get stunned with the name.



Short circuiting occurs when you do logical operations like ‘AND’ and ‘OR’.

 “When we use short circuit operators only necessary evaluation is done rather than full evaluation.
Let me explain the above sentence with a proper example. Consider a simple “AND” condition code as shown below. Please note we have only one “&” operator in the below code.

if(Condition1 & Condition2)
{
}

In the above case “Condition2” will be evaluated even if “Condition1” is “false”. Now if you think logically it does not make sense to evaluate “Condition 2”, if “Condition 1” is false.It’s a AND condition right? , soif the first condition is false it means the complete ANDcondition is false and it makes no sense to evaluate “Condition2”.

There’s where we can use short circuit operator “&&”. For the below code “Condition 2” will be evaluated only when “Condition 1” is true.
if(Condition1 && Condition2)
{
}

The same applies for “OR” operation. For the below code (please note its only single pipe(“|”).)   “Condition2” will be evaluated even if “Condition1” is “true”. If you think logically we do not need to evaluate “Condition2” if “Condition1” is “true”.

if(Condition1 | Condition2)
{
}

So if we change the same to double pipe (“||”) i.e. implement short circuit operators as shown in the below code, “Condition2” will be evaluated only if “Condition1” is “false”.


if(Condition1 || Condition2)
{
}

Taken from the best selling interview question book .NETinterview question by Shivprasadkoirala 

Here’s an awesome video on concurrent generic collections in C#.

No comments: