Home
C#
bool.Parse, TryParse: Convert String to Bool
This page was last reviewed on Dec 24, 2022.
Dot Net Perls
Bool.Parse. We can convert a string to a bool. This can be done with bool.Parse or bool.TryParse—or by using a custom method with relaxed parsing rules.
Custom method. In the custom method, the strings TRUE and T should both evaluate to a true value. Further logic can be added—any truth value can be parsed.
true, false
bool
An example. Consider the bool.Parse and bool.TryParse methods built into the .NET Framework. These are the easiest to use in programs—you don't need to add custom code.
Note These methods can handle "true" and "false" and the uppercased versions of these things.
Warning Invalid strings, such as "Perls", should be used with the bool.TryParse method to avoid exceptions being thrown.
using System; class Program { static void Main() { string value = "true"; bool b = bool.Parse(value); Console.WriteLine(b); // [1] value = "False"; b = bool.Parse(value); Console.WriteLine(b); // [2] value = "Perls"; if (bool.TryParse(value, out b)) { Console.WriteLine("Not reached"); } } }
True False
BoolParser. This method parses a string to see if it matches an equivalent of yes. It tests for strings that should evaluate to true, and if none matches, it considers the default false.
Info In this example, the static BoolParser class has three methods that help identify the equivalent bool value for an input string.
And The first 2 methods, GetValue and IsFalse, call internally to IsTrue. The IsTrue method checks for true values.
Note IsTrue determines whether the input matches True, Yes, or 1. It is wrapped in a try-catch block.
Finally This exception handling could be useful if you call this method in your initialization code, where exceptions could be disastrous.
try
Exception
using System; class Program { static void Main() { Console.WriteLine(BoolParser.GetValue("true")); // True Console.WriteLine(BoolParser.GetValue("okay")); // False Console.WriteLine(BoolParser.GetValue("T")); // True Console.WriteLine(BoolParser.GetValue("False")); // False Console.WriteLine(BoolParser.GetValue("No")); // False Console.WriteLine(BoolParser.GetValue("maybe")); // False Console.WriteLine(BoolParser.GetValue("YES")); // True Console.WriteLine(BoolParser.GetValue("TRUE ")); // True Console.WriteLine(BoolParser.GetValue("f")); // False Console.WriteLine(BoolParser.GetValue("1")); // True Console.WriteLine(BoolParser.GetValue("0")); // False Console.WriteLine(BoolParser.GetValue(bool.TrueString)); // True Console.WriteLine(BoolParser.GetValue(bool.FalseString)); // False } } /// <summary> /// Parse strings into true or false bools using relaxed parsing rules /// </summary> public static class BoolParser { /// <summary> /// Get the boolean value for this string /// </summary> public static bool GetValue(string value) { return IsTrue(value); } /// <summary> /// Determine whether the string is not True /// </summary> public static bool IsFalse(string value) { return !IsTrue(value); } /// <summary> /// Determine whether the string is equal to True /// </summary> public static bool IsTrue(string value) { try { // 1 // Avoid exceptions if (value == null) { return false; } // 2 // Remove whitespace from string value = value.Trim(); // 3 // Lowercase the string value = value.ToLower(); // 4 // Check for word true if (value == "true") { return true; } // 5 // Check for letter true if (value == "t") { return true; } // 6 // Check for one if (value == "1") { return true; } // 7 // Check for word yes if (value == "yes") { return true; } // 8 // Check for letter yes if (value == "y") { return true; } // 9 // It is false return false; } catch { return false; } } }
True False True False False False True True False True False True False
String input: true Bool result: True String input: false Bool result: False String input: t Bool result: True String input: f Bool result: False String input: yes Bool result: True String input: no Bool result: False String input: 1 Bool result: True String input: 0 Bool result: False String input: Is invalid Bool result: False
Note, usage. I needed this code when developing a configuration utility. I felt it would cause less worry for the users if the program was more accepting of slightly wrong values.
And With this class, the utility program is less of a burden because it can accept more input styles.
Tip No one needs to worry about uppercase or lowercase, or even whitespace. Users can be assured their input will be accepted.
A summary. We looked at the bool.Parse and bool.TryParse methods. We saw an easy way to implement bool parsing with many input variants. Finally we implemented a custom parser.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
No updates found for this page.
Home
Changes
© 2007-2024 Sam Allen.