1

Doing a few c# loops and if statements. Getting a highlight for unreachable code on a for loop. I can't quite figure this 1 out.

        public bool checkTime()
    {

        // Read values back from Json file
        var serializedList = File.ReadAllText(@filePathTimes);

        // getting a list of LockTime objects
        List<LockTime> deserializedList = (List<LockTime>)JsonConvert.DeserializeObject(serializedList, typeof(List<LockTime>));

        if (deserializedList.Count != 0)
        {

                // Grab whatever data you want from this list to store somewhere, such as a list of all Start and End integers.
                List<DateTime> intStartList = deserializedList.Select(entry => entry.Start).ToList();
                List<DateTime> intEndList = deserializedList.Select(entry => entry.End).ToList();

                //Then I do a foreach loop to go through every value in the start list and add the same located value to my listOfTimes (the list of LockTime objects with start and end)
                for (int x = 0; x < intStartList.Count; x++)
                {
                    TimeSpan start = new TimeSpan(intStartList[x].Hour, intStartList[x].Minute, intStartList[x].Second);
                    TimeSpan end = new TimeSpan(intEndList[x].Hour, intEndList[x].Minute, intEndList[x].Second);
                    TimeSpan now = DateTime.Now.TimeOfDay;
                    LockTime theTime = new LockTime(intStartList[x], intEndList[x]);
                    _lockTimes.Add(theTime);
                    if((now > start) && (now < end))
                    {
                        return true;
                    }

                        return false;

                }
        }
        return false;
    }

The highlight for unreachable code is coming up on the x++ on the for loop. Any ideas why this is?

JARRRRG
  • 917
  • 2
  • 14
  • 44

2 Answers2

11

That's because regardless of what happens, the code inside the loop will execute either return true; or return false;.

The loop won't loop.

Lasse V. Karlsen
  • 380,855
  • 102
  • 628
  • 825
4

The reason is because you are calling:

return true

or

return false

In the loop so it will ALWAYS exit after going round once.

Belogix
  • 8,129
  • 1
  • 27
  • 32
  • Why it should give a warning when there is no more code to execute in the loop? I guess OP shown different code. – Sriram Sakthivel Apr 29 '14 at 08:11
  • @SriramSakthivel - The warning is because the compiler can see that because of the `return` it will exit after one loop regardless of size of the list. So, it "knows" that if `x = 10` it will still only loop once which is probably not intended action. – Belogix Apr 29 '14 at 08:13
  • @SriramSakthivel - Care to elaborate / explain? How will `x++` ever be reached if OP is `return` after one loop? – Belogix Apr 29 '14 at 08:15
  • I stand corrected. Now I got it warning is for `x++` thanks :) – Sriram Sakthivel Apr 29 '14 at 08:17