whats wrong with this code? It keeps giving me an "unreachable code detected " exception

public static int search(string Registration)
        {
            // this method will search for registration, if found it will return the index value , else it will return max value + 1          

            for (int x = 0; x < numOfRowsCars; x++)
            {
                reg = ds1.Tables["tblCars"].Rows[x][2].ToString();
                MessageBox.Show(reg);
                if (Registration == reg)
                {
                    // Then return the index of the registration number 
                    return x;
                }
                else
                {
                    // Then return the max index + 1
                    return numOfRowsCars;
                }
            }                              
        }

An exception? Or a warning?

Also, I suggest you put the else return value outside of the loop. If you're trying to check wether a string is inside an array, putting the second return into the else statement will quit your loop right after the validation didn't get the searched value in the first try (given that it is not on the first position in the array). This may also solve your "unreachable code detected" warning.

public static int search(string Registration)
    {
        // this method will search for registration, if found it will return the index value , else it will return max value + 1          
        for (int x = 0; x < numOfRowsCars; x++)
        {
            reg = ds1.Tables["tblCars"].Rows[x][2].ToString();
            MessageBox.Show(reg);
            if (Registration == reg)
            {
                // Then return the index of the registration number 
                return x;
            }//move else to end of row
        }
        // Then return the max index + 1
        return numOfRowsCars;
    }

Thanks! I'm such a noob! haha, thanks for the valuable lesson. Much appreciated!

Sure! It can happen to anyone :P

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.