OneBite.Dev - Coding blog in a bite size

Convert Variable From String To Boolean In C#

Code snippet for how to Convert Variable From String To Boolean In C# with sample and detail explanation

When working in C#, there might be scenarios where you come across the need to convert variables from one datatype to another. A common conversion required is from string to boolean. This article will be a guide on how to simply and effectively execute this conversion.

Code snippet for String to Boolean Conversion

Suppose you have the following string which represents a boolean value.

string str = "True";

You can convert this string value to boolean as follows:

bool result = bool.Parse(str);
Console.WriteLine(result);  // Output: True

Now, if you also desire to handle conversion exception, we can use bool.TryParse as below:

bool result;
bool isParsed = bool.TryParse(str, out result);

if (isParsed)
{
    Console.WriteLine(result);  // Output: True
}
else
{
    Console.WriteLine("Invalid boolean value"); 
}

Code Explanation for String to Boolean Conversion

The above bool.Parse() method in C# is used to convert the specified string representation of a logical value to its boolean equivalent. It returns true or false depending upon the input.

In the first code snippet, we declared a string variable str and assigned it a value of “True”. Next, we use the bool.Parse(str) method to convert the string “True” to its boolean equivalent.

In the case of a misfit string value (not “True” or “False”), the bool.Parse() method will throw a FormatException. Hence, if you are unsure of the string content and want to avoid exceptions, it’s safer to use bool.TryParse(), as shown in the second snippet.

bool.TryParse() attempts to convert the string to a bool and doesn’t throw an exception if conversion fails. Instead, it returns ‘false’. This function takes two arguments: the first is the string to convert and the second is an out parameter of type bool where it stores the result of the conversion. If the conversion is successful, it will return ‘true’ and the result of conversion is stored in the out variable. If conversion fails, it will return ‘false’ and the out variable will contain ‘false’.

c-sharp