In trying to parse some URL parameters in a project I realised that Boolean.Parse and Boolean.TryParse work in slightly different ways and that neither was broad enough for my purposes.

Boolean.TryParse

Boolean.TryParse takes a string input parameter and a Boolean output parameter and returns a Boolean specifying whether the input parameter was a Boolean. This only identifies a value as being a Boolean if it’s some variation of “true” or “false”.

using System;

public class Example
{
	public static void Main()
	{
		string[] values = { null, String.Empty, "True", "False", 
			"true", "false", "    true    ", "0", 
			"1", "-1", "string" };
		foreach (var value in values) {
			bool flag;
			if (Boolean.TryParse(value, out flag))
				Console.WriteLine("'{0}' --> {1}", value, flag);
			else
				Console.WriteLine("Unable to parse '{0}'.", 
					value == null ? "<null>" : value);
		}                                     
	}
}
// The example displays the following output:
//       Unable to parse '<null>'.
//       Unable to parse ''.
//       'True' --> True
//       'False' --> False
//       'true' --> True
//       'false' --> False
//       '    true    ' --> True
//       Unable to parse '0'.
//       Unable to parse '1'.
//       Unable to parse '-1'.
//       Unable to parse 'string'.

Boolean.Parse

Boolean.Parse works in a similar way to Boolean.TryParse but returns an exception if the input parameter is not a Boolean.

ToBoolean

For my purposes I wanted something that along with parsing the strings “true” and “false” would also work for “1” and “0” (I added a few additional values as well). In order to do this I just created my own extension method that can be called from any string. This returns a bool? as I wanted a NULL value to be returned if the input string isn’t a Boolean rather than it throwing an exception.

public static class StringExtensions
{
	public static bool? ToBoolean(this string value)
	{
		switch (value.ToLower().Trim())
		{
			case "true":
				return true;
			case "t":
				return true;
			case "yes":
				return true;
			case "y":
				return true;
			case "1":
				return true;
			case "false":
				return false;
			case "f":
				return false;
			case "no":
				return false;
			case "n":
				return false;
			case "0":
				return false;
			default:
				return null;
		}
	}
}

0 Comments

Leave a Reply

Avatar placeholder

Your email address will not be published. Required fields are marked *