tdkr80 tdkr80 - 1 year ago 161
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;
return false;

return false;

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

Answer Source

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);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download