Convert.ToBoolean

  • Thread starter Thread starter simonZ
  • Start date Start date
S

simonZ

Why this don't work:

Boolean test;
String testValue;

testValue="0";
test=System.Convert.ToBoolean(testValue);


How can I convert string to boolean?

This works, but I need to use 2 conversions:
test=Convert.ToBoolean(Convert.ToInt16(testValue));

Can this be done with single conversion?

Regards,Simon
 
...
Why this don't work:

Boolean test;
String testValue;

testValue="0";
test=System.Convert.ToBoolean(testValue);

How can I convert string to boolean?

By using the string equivalents of the boolean values:

"True" or "False".
This works, but I need to use 2 conversions:
test=Convert.ToBoolean(Convert.ToInt16(testValue));

Can this be done with single conversion?

Nope.

The question should rather be:

Why do you use a string to contain a
numeric value in the first place?

A Boolean can only have one of two values: true or false

If you want to use a string to contain a boolean value, you could use the
values I mentioned above.

You can also convert from a numeric value to a boolean, but another question
should be:

Why does the conversion from a numeric value
to a Boolean work at all?

To simplify wrapping of legacy code in C/C++ where boolean values actually
*were* numeric values (0=false, 1=true), but there were no direct
conversions from strings to boolean values in those languages either.

So, as a conclusion, these two alternatives gives the "single-conversions":

String testValue = "False";
Boolean test = System.Convert.ToBoolean(testValue);

---------------------------------------------------

int testValue = 0;
Boolean test = System.Convert.ToBoolean(testValue);


// Bjorn A
 
simonZ said:
Why this don't work:

Boolean test;
String testValue;

testValue="0";
test=System.Convert.ToBoolean(testValue);

Because "0" isn't the string representation of any Boolean value. This
is C#, not C or C++.
How can I convert string to boolean?

Either Convert.ToBoolean, or Boolean.Parse. Both want a string
representation of a Boolean value - ie, Boolean.TrueString ("True") or
Boolean.FalseString ("False").

This is all in the docs.
 
Hi,

See Convert.ToBoolean it has a very good explanation of why it fails.

how to do it?, well what about this:

boolean b = testvalue.Equals( "0" );
 
...
See Convert.ToBoolean it has a very good explanation of why it fails.

how to do it?, well what about this:

boolean b = testvalue.Equals( "0" );

Which gives the reversed result... ;-)

You probably mean:

boolean b = !testvalue.Equals( "0" );


/// Bjorn A
 

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

Back
Top