Mar 29 2007

The difference between && and &

Category: C#fossmo @ 03:24
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:

and.png

Tags:

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Mar 26 2007

New blog

Category: fossmo @ 16:11
This is my first post in my new blog.

Tags:

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5