📜  c# string to bool - C# (1)

📅  最后修改于: 2023-12-03 15:29:46.290000             🧑  作者: Mango

C# String to Bool

In C#, we can easily convert a string to a bool using the Convert.ToBoolean(string value) method or by using bool.TryParse(string value, out bool result).

Using Convert.ToBoolean Method

The Convert.ToBoolean method returns a boolean value that indicates whether the string input represents a true or false value.

string input = "True";
bool output = Convert.ToBoolean(input);
Console.WriteLine(output); // Output: True

In the above code, we convert the string "True" to the bool value True.

If the string cannot be converted to either True or False, an exception will be thrown. To avoid this, you can wrap the Convert.ToBoolean method in a try-catch block:

string input = "notbool";
try {
    bool output = Convert.ToBoolean(input);
    Console.WriteLine(output);
} catch (FormatException) {
    Console.WriteLine($"Unable to parse '{input}' to bool.");
}
Using bool.TryParse Method

The bool.TryParse method tries to convert a string to a bool and returns a boolean value that indicates whether the operation was successful.

string input = "False";
bool output;
if (bool.TryParse(input, out output)) {
    Console.WriteLine(output); // Output: False
} else {
    Console.WriteLine($"Unable to parse '{input}' to bool.");
}

In the above code, we convert the string "False" to the bool value False. If the conversion fails, we display an error message.

Conclusion

Converting a string to a bool in C# is a simple task that can be accomplished using Convert.ToBoolean(string value) or bool.TryParse(string value, out bool result). Always remember to handle invalid inputs using exception handling or a simple if-else statement!