NullReferenceException when checking for null

I already checked for this one and I understand at this point that this is probably the intended behavior, but what I wish to know is if there is any way to avoid error popping up at all, for example; some other method of checking.

My example is a light switch which can have as many light source children as you put in it and numerate them (example: lightSource1, lightSource2…) and it is launching them with this script:

int j=1;
while(gameObject.transform.FindChild ("lightSource"+j).light!=null)
{
//toggle script
++j;
}

As soon as it reaches “j” that is greater than the number of light sources, it throws in an error, which is an annoyance while working with new scripts (especially as what it is reporting is intended occurance).

Thread for this already exists here:

but provides no answer on what to do with it.

The error is: “NullReferenceException: Object reference not set to an instance of an object”

It produces a null reference exception because this part:

gameObject.transform.FindChild ("lightSource"+j)

…comes back null, and you are tying to access the null with this part:

.light

You can do it this way:

GameObject go;
int j = 1;

do {
    go = gameObject.transform.FindChild ("lightSource"+j);
    if (go != null && go.light != null) {
         //toggle script
    }
} while (go != null);

Another way to approach this problem, assuming these children are the only children with a Light component:

Light[] lights = FindComponentsInChildren<Light>();
foreach (Light light in lights) {
    //toggle
}