tdkr80 tdkr80 - 3 months ago 31
C# Question

Unreachable Code Detected (Why?)

So, why is it that there is unreachable code detected in this code:

public bool GetKeyPressed(KeyCode key)
{
for (int i = 0; i < keys.Count; i++)
if (keys[i].key == key && keys[i].pressed)
return true;
else
return false;

return false;
}


The index (i) is apparently unreachable ... why?

Answer

Your code has a loop that evaluates once, therefore the first iteration will always return.

If that's what you want, just say that,

return keys[0].key == key && keys[0].pressed;

If however (which is what I suspect here), you want to return true if any in the array meets your test, then use LINQ's Any(),

return keys.Any(k => k.key == key && k.pressed);