2
DB.DBEntities ent = new DB.DBEntities();

foreach (var brn in ent.Sites.ToList()) 
{
     //Do work                 
}

If I try above code, it gives Unreachable code on var branch

But if I store the list in another list object and iterate on it, no warning is given.(As below)

DB.DBEntities ent = new DB.DBEntities();
List<DB.Site> list = ent.Sites.ToList();

foreach (var brn in list) 
{
     //Do work                 
}

Can some one please explain why does this happen?

dcastro
  • 66,540
  • 21
  • 145
  • 155
Wasif Subzwari
  • 199
  • 3
  • 13
  • 1
    Is there some code between the initialization of `ent` and the `foreach` loop ? – tschmit007 Jul 21 '14 at 10:01
  • 2
    What's inside the `foreach`? Any `break` statements or anything, like this one? http://stackoverflow.com/questions/1476438/c-sharp-unreachable-code-detected. Also, take a look at this: http://stackoverflow.com/questions/13067886/why-is-the-code-in-my-foreach-unreachable-exact-copy-of-working-code-thats-bee – shree.pat18 Jul 21 '14 at 10:06
  • No, absolutely nothing in between. No break statements either – Wasif Subzwari Jul 21 '14 at 10:32

0 Answers0