In this article, we are going to learn how to convert string to bool in C#. We are going to see the various ways to accomplish that using the different methods: Convert.ToBoolean, bool.Parse, and boolTryParse

To download the source code for this article, you can visit our GitHub repository.

So, let’s talk more about that.

Using Convert.ToBoolean to Convert String to Bool

The Convert.ToBoolean method has a lot of overloads. But in our example, to convert string to bool, we are going to use an overload that uses only a single string parameter:

Support Code Maze on Patreon to get rid of ads and get the best discounts on our products!
Become a patron at Patreon!

Convert.ToBoolean(string stringName);

For the conversion to be successful the parameter that we pass must be either true, false or null. This method ignores case letters as well as white spaces that occur before or after the string passed. Hence, passing any other value besides these will throw a FormatException and the conversion will fail. To avoid breaking our application, we have to handle these Exceptions.

So, let’s see how this works with an example:

public static void ToBooleanMethod()
{
    string[] validString = { null, "true", "True", "    true   ", "false", "False", "    false" };

    string[] invalidString = { "", string.Empty, "t", "    yes   ", "-1", "0", "1" };

    var values = validString.Concat(invalidString);

    foreach (var value in values)
    {
        try
        {
            Console.WriteLine($"Converted '{value}' to {Convert.ToBoolean(value)}.\n");
        }
        catch (FormatException)
        {
            Console.WriteLine($"Unable to convert '{value}' to a Boolean.\n");
        }
    }
}

Here, we concatenate both arrays in a single collection and iterate through each element trying to convert it to bool. So, once we execute this method, it will successfully convert all the strings within the validString array to bool. But it will not convert the strings from the invalidString  array.

Using bool.Parse to Convert String to Bool

bool.Parse is another method we can use for converting string to bool in C#.  The overload of this method we are going to use has one string parameter:

public static bool Parse (string stringName);

For the conversion to be successful the parameter that we pass must be either true or false. Also, this method ignores case letters as well as white spaces that occur before or after the string. That said if we pass null or any other value it will throw an Exception and the conversion will fail:

public static void ParseMethod()
{
    string[] validString = { "true", "True", "    true   ", "false", "False", "    false" };

    string[] invalidString = {null, "", string.Empty, "t", "    yes   ", "-1", "0", "1" };

    var values = validString.Concat(invalidString);

    foreach (var value in values)
    {
        try
        {
            Console.WriteLine($"Converted '{value}' to {bool.Parse(value)}.\n");
        }
        catch (Exception)
        {
            Console.WriteLine($"Unable to convert '{value}' to a Boolean.\n");
        }
    }
}

When we run our application, our output will be similar to the output we got when using Convert.ToBoolean. However, the only difference will be the output when we pass a null value into the bool.Parse method.

Using the bool.TryParse Method

Lastly, we can use bool.TryParse method to convert string to bool. To do this, we are going to use an overload of the method that has two parameters and returns a bool:

public static bool TryParse (string? stringName, out bool booleanValue);

bool.TryParse returns true if the string was converted successfully or false if it wasn’t. When we pass true or false as the parameter, the conversion will be successful. On the contrary, the conversion fails if we pass null or any value not equal to true or false. Similar to Convert.ToBoolean, this method ignores case letters as well as white spaces.  

The out parameter contains the result of the conversion. When the conversion fails, the value of the out parameter will be false

So, let’s see how this works with an example:

public static void TryParseMethod()
{
    string[] validString = { "true", "True", "    true   ", "false", "False", "    false" };

    string[] invalidString = { null, "", string.Empty, "t", "    yes   ", "-1", "0", "1" };

    var values = validString.Concat(invalidString);

    foreach (var value in values)
    {
        if (bool.TryParse(value, out bool booleanValue))
        {
            Console.WriteLine($"Conversion successful: '{value}' to {booleanValue}.\n");
        }
        else
        {
            Console.WriteLine($"Conversion Failed: '{value}' to {booleanValue}.\n");
        }
    }
}

As you can see, we are not handling exceptions here as we did with our previous two examples. This means that bool.TryParse is a more suitable method to use if we do not want to handle exceptions when the conversion fails.

Conclusion

In this article, we have learned how to convert string to bool using different methods and examples. We’ve even seen that with the bool.TryParse method, we don’t have to handle exceptions during the conversion.

Liked it? Take a second to support Code Maze on Patreon and get the ad free reading experience!
Become a patron at Patreon!