Unreachable code detected

D

dfetrow410

Can I do this in an if statement?


public string getClass()
{
counta = counta + 1;


if (counta < 2 )
{
MyClass mc = new MyClass();
setTheClass("Blue"); *********** Unreachable code detected
}
else
{
return ("");
}
}




class MyClass
{
private string x;
public void SetClass(string i)
{
x = i;
}
public string GetClass()
{
return x;
}
}
 
G

Guest

What exactly are you trying to do in the if statement? Are you saying that
you're getting a warning about unreachable code with the sample you showed?
 
T

Tim Wilson

That doesn't look like unreachable code to me. Maybe I've overlooked
something. Are you sure you don't have a return statement, or something,
before the call to the "setTheClass" method? It looks like you're missing a
return in there.

if (something)
{
return a;
}
else
{
return b;
}

.... or ...

if (something)
{
return a;
}
return b;
 
D

dfetrow410

Trying to set a var
I get blue squig under "MyClass" says "Unreachable code detected "

public string getClass()
{
counta = counta + 1;


if (counta < 2 )
{
return ("rank_1");
MyClass mc = new MyClass();
mc.SetClass("rank_1");
}

else
{
return ("");
MyClass mc = new MyClass();
mc.SetClass("rank_6");

}
}
 
T

Tim Wilson

The "returns" need to be the last line in a code block. So what you're
attempting to do now is return before creating an instance of MyClass. Thus,
at that point the two lines of code under the return statements will never
be reached. Try this instead.

public string getClass()
{
counta++;
MyClass mc = new MyClass();
if (counta < 2 )
{
string rank = "rank_1";
mc.SetClass(rank);
return rank;
}
else
{
mc.SetClass("rank_6");
return String.Empty;
}
}
 
J

Jon Skeet [C# MVP]

Trying to set a var
I get blue squig under "MyClass" says "Unreachable code detected "

public string getClass()
{
counta = counta + 1;


if (counta < 2 )
{
return ("rank_1");
MyClass mc = new MyClass();
mc.SetClass("rank_1");
}

else
{
return ("");
MyClass mc = new MyClass();
mc.SetClass("rank_6");

}
}

Yes, now you've posted different code, we can see why - "return"
returns immediately. In this case you can just move the return
statements to the ends of the blocks.

As a side note, this is an important example of why it's important to
post real code - the same code which is producing the problem -
especially if you don't understand exactly what's going on.
 
D

dfetrow410

You da man Tim. Sorry about the code change. I had old code in my text
editor

YOU GUYS SAVE LIVES ON HERE.

Thanks for takeing the time to help us newbies to C#
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top