Some days ago I came across something i haven't tought about. What is the difference between & and && in a if-statement?
It turns out that && only validates the first condition in the statement if it is false. & validates both conditions regardless of condition one.
This is handy if you have to check if a object is null (condition one) before you check for something else in the object (condition two).
Here are some example code:
class Program
{
static void Main(string[] args)
{
Console.WriteLine("One &:");
if ((testOne()) & (testTwo()))
{
Console.WriteLine("Inside if-statement");
}
Console.WriteLine("\nTwo &:");
if ((testOne()) && (testTwo()))
{
Console.WriteLine("Inside if-statement");
}
Console.WriteLine("\nPress a key!");
Console.ReadKey();
}
static bool testOne()
{
Console.WriteLine("Inside testOne");
return false;
}
static bool testTwo()
{
Console.WriteLine("Inside testTwo");
return false;
}
}
Result:
Tags: