CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 4 of 4
  1. #1
    Join Date
    May 2003
    Location
    Germany
    Posts
    936

    Convert string to bool

    Hi there,

    how do I convert a string to a bool?
    I get a string with "0" for false and "1" for true. At the moment I convert it twice, but I think that is not the best way.

    Can someone give me a hint?

    at the moment I do this:
    Code:
    Convert.ToBoolean(Convert.ToInt32(myString))

  2. #2
    Join Date
    Feb 2001
    Location
    AZ
    Posts
    201
    bool bvalue = (svalue == "1" ? true : false);


    Regards,
    Hal
    up·grade (up'gräd'),
    to take out old bugs
    and put in new ones.

  3. #3
    Join Date
    Oct 2009
    Posts
    1

    Re: Convert string to bool

    Your question was not at all clear. It depends on what you have in your 'string' value.

    If you have 'true' or 'false' in your string value then all you need to do to convert the string value to a boolean is as follows:

    bool booleanValue = Convert.ToBoolean(myString);

    If you have '0' or '1' in your string value then

    bool bvalue = (svalue == "1" ? true : false);

    is what you need (noting that any value other than '1' will set bvalue to false).

  4. #4
    Join Date
    Jun 2001
    Location
    Melbourne/Aus (C# .Net 4.0)
    Posts
    686

    Re: Convert string to bool

    Slightly more concise...
    Code:
                String sValue = "0"; // or "1";
    
                Boolean bValue = sValue.Equals("1");
    Rob
    -
    Ohhhhh.... Old McDonald was dyslexic, E O I O EEEEEEEEEE.......

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured