i dont understand why sometimes this code works and sometimes i get an infinite loop - C#