Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Unreachable code detected

I'm getting a "Unreachable code detected" message in Visual Studio at the point i++ in my code below. Can you spot what I've done wrong?

try
{
    RegistryKey OurKey = Registry.CurrentUser;
    OurKey.CreateSubKey("Software\\Resources\\Shared");
    OurKey = OurKey.OpenSubKey("Software\\Resources\\Shared", true);
    for (int i = 0; i < cmbPaths.Items.Count; i++) //<---- problem with i
    {
        OurKey.SetValue("paths" + i, cmbPaths.Items[i]);
        break;
    }
}
like image 593
Jamie Avatar asked Sep 25 '09 09:09

Jamie


3 Answers

The problem is that this actually isn't a loop. You don't have any condition on the break so you could equivalently write something like

if(cmbPath.Items.Count > 0)
{
   OurKey.SetValue("paths" + 0, cmbPaths.Items[0]);
}

Alternatively you have to correct with something like

for (int i = 0; i < cmbPaths.Items.Count; i++) 
{
   OurKey.SetValue("paths" + i, cmbPaths.Items[i]);

   if(someConditionHolds)
      break;
}
like image 109
Juri Avatar answered Oct 22 '22 20:10

Juri


You're breaking out of the loop before the end of the first iteration.

like image 36
wefwfwefwe Avatar answered Oct 22 '22 22:10

wefwfwefwe


The problem is that because you break; in the loop with no chance of it doing anything else, the increment of i (i++) will never be reached.

like image 41
Daniel Elliott Avatar answered Oct 22 '22 22:10

Daniel Elliott