C# Unreachable code detected
Asked Answered
H

5

11

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;
    }
}
Helainehelali answered 25/9, 2009 at 9:56 Comment(0)
C
25

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;
}
Cosmology answered 25/9, 2009 at 9:59 Comment(0)
S
12

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

Sclerometer answered 25/9, 2009 at 9:57 Comment(1)
just delete the line that says break;Sclerometer
F
4

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.

Fluidextract answered 25/9, 2009 at 9:59 Comment(0)
E
1

Although your problem is solved i need to tell you this, you can just using the CreateSubKey() method for your purpose. I think It's a better choice. :)

//Creates a new subkey or opens an existing subkey for write access.
var ourKey = Registry.CurrentUser.CreateSubKey("Software\\Resources\\Shared");
Europium answered 12/5, 2012 at 21:2 Comment(0)
A
1

You can also end up getting unreachable code if you use say for example Entity Framework, and you didn't add that reference to that project.

Say you have several projects like A Data Layer Project, a Domain Classes, then you create a console app for testing or whatever and you reference where your dbcontext is at, but if you don't use say nuget and add in EF, you will get code unreachable when trying to write a loop etc...

Atterbury answered 13/3, 2013 at 23:15 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.