Mohanapriya R Mohanapriya R
Updated date Jul 10, 2024
In this blog, we will explore converting strings to booleans in C#.

Converting Strings to Boolean in C#:

In C#, converting a string to a boolean involves interpreting a string value as either "true" or "false." The bool.Parse() and bool.TryParse() methods are used for this purpose. The bool.Parse() method throws an exception if the conversion fails, while the bool.TryParse() method handles errors without causing program termination.

using System;

class StringToBooleanConversion
    static void Main()
        // Sample strings for conversion
        string trueString = "true";
        string falseString = "false";
        string invalidString = "invalid";

        // Using bool.Parse()
        bool resultParseTrue = bool.Parse(trueString);
        bool resultParseFalse = bool.Parse(falseString);

        // Using bool.TryParse()
        bool resultTryParseTrue = false;
        bool resultTryParseFalse = false;
        bool.TryParse(trueString, out resultTryParseTrue);
        bool.TryParse(falseString, out resultTryParseFalse);

        // Output
        Console.WriteLine($"bool.Parse(\"{trueString}\"): {resultParseTrue}");
        Console.WriteLine($"bool.Parse(\"{falseString}\"): {resultParseFalse}");

        Console.WriteLine($"bool.TryParse(\"{trueString}\"): {resultTryParseTrue}");
        Console.WriteLine($"bool.TryParse(\"{falseString}\"): {resultTryParseFalse}");

        // Attempting to parse an invalid string
            bool invalidResult = bool.Parse(invalidString);
        catch (Exception ex)
            Console.WriteLine($"Exception when parsing \"{invalidString}\": {ex.Message}");
  • bool.Parse(trueString) successfully converts the string "true" to true.
  • bool.Parse(falseString) converts the string "false" to false.
  • bool.TryParse(trueString, out resultTryParseTrue) and bool.TryParse(falseString, out resultTryParseFalse) demonstrate successful conversions using bool.TryParse().
  • The attempt to parse the invalid string "invalid" using bool.Parse() results in an exception.


bool.Parse("true"): True
bool.Parse("false"): False
bool.TryParse("true"): True
bool.TryParse("false"): False
Exception when parsing "invalid": String was not recognized as a valid Boolean.

Comments (0)

There are no comments. Be the first to comment!!!