I have been reviewing some code where a clear appreciation of the difference between ‘&’ and ‘&&’ is not fully realized. The humble ‘&’ provides a distinct way to provide a logical ‘AND’. Let us take this simple class with a single string array associated with it. Lets ignore the obvious lack of properties for a moment…

public class SimpleClass
{
    public string[] SimpleProperty;
}

Now when we go to use this class we would want to ensure that the SimpleString array is not null before actually performing any operations on it. One way could be to nest the if statement as follows:

if(foo.SimpleProperty != null)
{
    if(foo.SimpleProperty.Count() > 0)
    {
        MessageBox.Show("Success");
    }
}

This might negatively effect your Cyclomatic Complexity and we could not have such an offense ;) So a simple AND (‘&’) would be useful but as mentioned before this is a logical AND, as a result both values are always evaluated. So the following code would actually fail in the event of a SimplyProperty actually being null.

if(foo.SimpleProperty != null & foo.SimpleProperty.Count() > 0) //this could give you a null exception!!
{
    MessageBox.Show("Success");
}

So to the use of ‘&&’. With this technique the JIT compiler always checks the validity of the first expression and if it is false will not even evaluate the second (or subsequent) expressions in the if statement.

if(foo.SimpleProperty != null && foo.SimpleProperty.Count() > 0) //this is safe from null exceptions!! 
{
    MessageBox.Show("Success");
}

Simple, basic and true!!



Comment Section

Comments are closed.