convert int values to bool

  • Thread starter Thread starter puzzlecracker
  • Start date Start date
P

puzzlecracker

Is it possible, in a clean way, to convert int values too bool
int i=10;

bool b=(bool)i;


instead of doing b=(i>0);
 
Is it possible, in a clean way, to convert int values too bool
int i=10;

bool b=(bool)i;

instead of doing b=(i>0);

I'd argue the statement should be:
bool b = (i != 0)

but this will work too:
bool b = Convert.ToBoolean(i);
 
puzzlecracker said:
Thanks, that's what I was looking for!

And guess how it's implemented?

public static bool ToBoolean(int value) {
return (value != 0);
}

:)
 
puzzlecracker said:
Sweet, what about the reverse?

You mean:

public static int ToInt32(bool value)
{
if (!value)
{
return 0;
}
return 1;
}

?

I don't know why it is not using the ?: operator.

Arne
 
You mean:
public static int ToInt32(bool value)
{
if (!value)
{
return 0;
}
return 1;
}

?

I don't know why it is not using the ?: operator.

Did you look at the source code or use a decompiler? The MSIL doesn't
provide any distinction that a decompiler could use between an if/else vs
tertiary operator.
 
Did you look at the source code or use a decompiler?  The MSIL doesn't
provide any distinction that a decompiler could use between an if/else vs
tertiary operator.






- Show quoted text -

right.

it basically converts to one and the same

-Cnu
 
Ben said:
Did you look at the source code or use a decompiler? The MSIL doesn't
provide any distinction that a decompiler could use between an if/else vs
tertiary operator.

Reflector.

So it could actually have been a ?: operator ?

Well - easy to test.

public static class ToBeOrNotToBe
{
public static int Foo(bool v)
{
return v ? 1 : 0;
}
public static int Bar(bool v)
{
if(v)
{
return 1;
}
else
{
return 0;
}
}
}

csc and reflector:

public static class ToBeOrNotToBe
{
// Methods
public static int Bar(bool v)
{
if (v)
{
return 1;
}
return 0;
}

public static int Foo(bool v)
{
return (v ? 1 : 0);
}
}

csc /o+ and reflector:

public static class ToBeOrNotToBe
{
// Methods
public static int Bar(bool v)
{
if (v)
{
return 1;
}
return 0;
}

public static int Foo(bool v)
{
if (!v)
{
return 0;
}
return 1;
}
}

Yes - it looks as if the ?: has been used after all.

Arne
 
Back
Top