Wednesday, October 31, 2007

How many ways to represent True and False

I was recently serializing data from both the database and user input, and it made me reflect on how many ways you can represent a boolean value as a literal string. For an English-language app (no globalization), here are several ways to represent a boolean:

TRUE / FALSE - converting from a literal string.
T / F - users who only want to enter the first character.
Yes / No - non-technical users who want "friendly" terms.
Y / N - again, users who want to only enter the first character.
1/0 - A bit, such as how SQL Server stores booleans.

And of course, the first three options can be case insensitive and trimmed white space (i.e. "tRUe" becomes "TRUE").

I had talked about using Convert.ToString to convert different objects to string, so I'd initially look at it's related method: Convert.ToBoolean. But one quickly sees that that won't handle all the cases (and with good reason).
The only literal string it takes from this group is "true"/"false". For example, it would handle converting the integer 1, but not the literal string "1".
Having a single function that just converts these different inputs to a boolean is a nice convenience.
Here's a sample:
public static bool ConvertToBoolean(string strVal)
{
if (string.IsNullOrEmpty(strVal))
return false;
strVal = strVal.ToUpper().Trim();
if (strVal == "TRUE" strVal == "T" strVal == "1" strVal == "YES" strVal == "Y") return true; else if (strVal == "FALSE" strVal == "F" strVal == "0" strVal == "NO" strVal == "N")
return false;
else
throw new ArgumentException("Cannot convert '" + strVal + "' to Boolean.");}

No comments: