False Unreachable Code Detected warningS

The code below shows the warning, with the “i” in “i++” underlined in Visual Studio. The code functions exactly as it should do, so I am not sure why I am getting this error. Is there anyway to fix this? If not, can I suppress the warning?

    public static List<Ability> LoadExpertiseAbilityList(AbilityExpertise type)
    {
        List<Ability> temp = new List<Ability>();

        for (int i = 0; i < abilityDatabase.Count; i++)
        {
            Ability a = abilityDatabase[i];
            if (a.expertise == type)
                temp.Add(a);
            return temp;
        }
        return null;
    }

Are you sure this code is working as you intend? (Hint, Visual Studio is correct in the warning it is giving you :)).

Try stepping through this code in the debugger. Do you notice anything about what happens?

Have you tried any test cases where more than 1 ability gets returned?

1 Like

return temp; will quit the method (and for loop) right on the first iteration, i++ will never be executed.

Btw, I strongly suggest you to use some more descriptive names for your variables.

1 Like

For a utility method the ‚a‘ is fine. The temp I don‘t like, as it could be anything. I would use ‚matchingAbilities‘.

Doh… I need to stop making these silly mistakes…

    public static List<Ability> LoadExpertiseAbilityList(AbilityExpertise type)
    {
        List<Ability> matchedAbilities = new List<Ability>();

        for (int i = 0; i < abilityDatabase.Count; i++)
        {
            Ability a = abilityDatabase[i];
            if (a.expertise == type)
            {
                matchedAbilities.Add(a);
            }
        }
        return matchedAbilities;
    }

Hoping this is now correct? Not got unity open right now to test…

Hi ItzChris92,
Out of interest, would you have got to the answer from just the first 2 responses on this thread alone?

I think that it will be valuable for you to become comfortable with debugging code through when confronted with issues where, for example, code is not acting as you expect. :slight_smile:

I figured it out after your first comment… even though I had gone through the code line by line with the issue staring me in the face and I didn’t see it :confused:

I debug my code a lot, but I hadn’t thought to try to add more abilities to my database (I only have one currently, just setting the base for everything) as I thought the method was working correctly because it wasn’t returning null.

Appreciate the help guys. Stay tuned for more ridiculous overlooked mistakes on my part :smile:

1 Like