Unity C# Noob Errors

I have noticed while answering questions at Unity Answers that there are some that come up ovr and over with first time programmers. Rather then answer them over and over, I decided to start a list of them here:

Question: Why am I getting this error:

Error: A local variable cannot be used before it is declared: closest.

My code looks like this:

GameObject FindClosestEnemy() {
    GameObject[] possibleNewTargets;
    possibleNewTargets = GameObject.FindGameObjectsWithTag("enemy");
    GameObject closest;
    float distance = lightningJumpRange;
    Vector3 position = transform.position;
 
    foreach (GameObject go in possibleNewTargets) {
        Vector3 diff = go.transform.position - position;
        float curDistance = diff.sqrMagnitude;
        if (curDistance < distance) {
            closest = go;
            distance = curDistance;
        }
    }
    return closest;
}

Answer:

In this line you declare the variable "closest" but you do not give it a value:
GameObject closest;

You initialize the variable "possibleNewTargets" here:
possibleNewTargets = GameObject.FindGameObjectsWithTag("enemy");
However the compiler knows that there may be no objects with the Tag enemy in which case the list possibleTargets will be empty.

The only place you assign a value to closest is in the following loop, But if possibleTargets is an empty list, that loop will never run. In that case, your function has no value in the variable "closest" to return at the end.

Fix this by initializing "closest" with null when you declare it, like this:
GameObject closes =nullt;