Expanding on jdphenix answer, I think we need to understand why your loop "evaluates once" and only then can we understand why there is "unreachable code".
public bool GetKeyPressed(Keys 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 for
loop has a single if-else
statement that makes up the body. The if
guard if satisfied returns true
otherwise it executes the next else
statement which returns false
. The net result is that at most a single cycle of the loop will be executed before control is returned to the calling method irrespective of the number of items in keys
.
It's more obvious if we look at the code via JetBrains Resharper:
The code may as well be written as:
public bool GetKeyPressed(Keys key)
{
for (int i = 0; i < keys.Count; ) // Look Ma, no i++ !!!
if (keys[i].key == key && keys[i].pressed)
return true;
else
return false;
return false;
}
Don't make the mistake of thinking that the very last return false
at the end of the method is not required because it is during the scenario where keys.Count == 0
Of course, formatting the code a bit more nicely goes a long way into revealing the problem that the first return false
is redundant and could be simplified as per un-lucky's answer:
keys
contains more than 1 key, it will return after the first iteration, and never find your desired key inside. Try removing the else in your for loop, e.g.for (int i = 0; i < keys.Count; i++) if (keys[i].key == key && keys[i].pressed) return true;
only.