Convert. toboolean ("1") = true?

Source: Internet
Author: User

If convert. toboolean ("1") = true, the following error is returned:
This string is not recognized as a valid Boolean value.

Check the system. Convert. toboolean (string) method,CodeAs follows:
Public static bool toboolean (string value)
{
If (value = NULL)
{
Return false;
}
Return bool. parse (value );
}

Obviously related to system. boolean. parse (string), the Code is as follows:
Public static bool parse (string value)
{
If (value = NULL)
{
Throw new argumentnullexception ("value ");
}
If (string. Compare (value, bool. truestring, true, cultureinfo. invariantculture) = 0)
{
Return true;
}
If (string. Compare (value, bool. falsestring, true, cultureinfo. invariantculture )! = 0)
{
Value = value. Trim ();
If (string. Compare (value, bool. truestring, true, cultureinfo. invariantculture) = 0)
{
Return true;
}
If (string. Compare (value, bool. falsestring, true, cultureinfo. invariantculture )! = 0)
{
Throw new formatexception (environment. getresourcestring ("format_badboolean "));
}
}
Return false;
}

You just need to check out bool. truestring to find out the cause.
Bool. truestring = "true ";
Bool. falsestring = "false ";

No wonder an error is thrown.

Check the system. Convert. toboolean (int16) method. The Code is as follows:
Public static bool toboolean (short value)
{
Return (value! = 0 );
}

Therefore, you can rewrite it to: Convert. toboolean (convert. toint16 ("1 "))

It seems that the system. Convert. toboolean (string) method is not very well designed. What do you say?

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.