Unreachable expression code detected

T

teddysnips

I'm new to C# - recent background mainly ASP.NET with VB.NET.

Anyhoot, I needed to create a C# statement analogous to VB's IIf:

VB.NET

Dim e As Boolean

e = IIf((CInt(MyVariable) > 0), True, False)

C#

bool e = ((int)MyVariable > 0) ? true : false;

It compiles and runs fine under C#, but the "false" word has a wiggly
green line underneath and the legend in the Warnings tab of the Errors
pane:

"Unreachable expression code detected"

Don't understand - can anyone shed light?

Thanks

Edward
 
M

Marc Gravell

First - you can just use:

bool e = ((int)MyVariable > 0);

Now; how is MyVariable defined? This should be fine - however, if
MyVariable is a "const", then the compiler will be evaluating this at
compile-time, so yes: the warning is correct.

Marc
 
P

Peter Bradley

You don't say what type MyVariable is, but it looks as though it casts to an
int OK.

So (int)MyVarialbe > 0 is already a boolean expression. Therefore I think
you only need:

bool e = (int)MyVariable > 0;

Of course if MyVariable is something that always resolves to a value greater
than zero when cast to an integer, then it will always resolve to true.

HTH


Peter
 
A

Alun Harford

I'm new to C# - recent background mainly ASP.NET with VB.NET.

Anyhoot, I needed to create a C# statement analogous to VB's IIf:

VB.NET

Dim e As Boolean

e = IIf((CInt(MyVariable) > 0), True, False)

C#

bool e = ((int)MyVariable > 0) ? true : false;

It compiles and runs fine under C#, but the "false" word has a wiggly
green line underneath and the legend in the Warnings tab of the Errors
pane:

"Unreachable expression code detected"

Don't understand - can anyone shed light?

The compiler knows that ((int)MyVariable > 0) is always true.

Alun Harford
 
T

teddysnips

You don't say what type MyVariable is, but it looks as though it casts to an
int OK.

So (int)MyVarialbe > 0 is already a boolean expression. Therefore I think
you only need:

bool e = (int)MyVariable > 0;

Doh! That's much more elegant. Thanks.

Edward
 

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