91

I have a string that can be either "0" or "1", and it is guaranteed that it won't be anything else.

So the question is: what's the best, simplest and most elegant way to convert this to a bool?

A-Sharabiani
  • 17,750
  • 17
  • 113
  • 128
Sachin Kainth
  • 45,256
  • 81
  • 201
  • 304
  • 3
    If any unexpected values can be in the input, consider to use TryParse (http://stackoverflow.com/questions/18329001/parse-to-boolean-or-check-string-value/18329085#18329085) – Michael Freidgeim Jan 30 '17 at 11:33

12 Answers12

184

Quite simple indeed:

bool b = str == "1";
Kendall Frey
  • 43,130
  • 20
  • 110
  • 148
85

Ignoring the specific needs of this question, and while its never a good idea to cast a string to a bool, one way would be to use the ToBoolean() method on the Convert class:

bool val = Convert.ToBoolean("true");

or an extension method to do whatever weird mapping you're doing:

public static class StringExtensions
{
    public static bool ToBoolean(this string value)
    {
        switch (value.ToLower())
        {
            case  "true":
                return true;
            case "t":
                return true;
            case "1":
                return true;
            case "0":
                return false;
            case "false":
                return false;
            case "f":
                return false;
            default:
                throw new InvalidCastException("You can't cast that value to a bool!");
        }
    }
}
Mohammad Sepahvand
  • 17,364
  • 22
  • 81
  • 122
  • 1
    Behavior of Convert.ToBoolean shown in http://stackoverflow.com/questions/7031964/what-is-the-difference-between-convert-tobooleanstring-and-boolean-parsestrin/26202581#26202581 – Michael Freidgeim Jan 30 '17 at 11:35
  • 2
    Feel [Boolean.TryParse](https://msdn.microsoft.com/en-us/library/system.boolean.tryparse(v=vs.110).aspx) is preferable when a lot of values need to be converted as it does not throw `FormatException` like [Convert.ToBoolean](https://msdn.microsoft.com/en-us/library/86hw82a3(v=vs.110).aspx). – user3613932 Jun 28 '18 at 01:17
51

I know this doesn't answer your question, but just to help other people. If you are trying to convert "true" or "false" strings to boolean:

Try Boolean.Parse

bool val = Boolean.Parse("true"); ==> true
bool val = Boolean.Parse("True"); ==> true
bool val = Boolean.Parse("TRUE"); ==> true
bool val = Boolean.Parse("False"); ==> false
bool val = Boolean.Parse("1"); ==> Exception!
bool val = Boolean.Parse("diffstring"); ==> Exception!
live-love
  • 48,840
  • 22
  • 240
  • 204
20
bool b = str.Equals("1")? true : false;

Or even better, as suggested in a comment below:

bool b = str.Equals("1");
GETah
  • 20,922
  • 7
  • 61
  • 103
8

I made something a little bit more extensible, Piggybacking on Mohammad Sepahvand's concept:

    public static bool ToBoolean(this string s)
    {
        string[] trueStrings = { "1", "y" , "yes" , "true" };
        string[] falseStrings = { "0", "n", "no", "false" };


        if (trueStrings.Contains(s, StringComparer.OrdinalIgnoreCase))
            return true;
        if (falseStrings.Contains(s, StringComparer.OrdinalIgnoreCase))
            return false;

        throw new InvalidCastException("only the following are supported for converting strings to boolean: " 
            + string.Join(",", trueStrings)
            + " and "
            + string.Join(",", falseStrings));
    }
mcfea
  • 1,129
  • 15
  • 22
5

I used the below code to convert a string to boolean.

Convert.ToBoolean(Convert.ToInt32(myString));
yogihosting
  • 5,494
  • 8
  • 47
  • 80
  • It is unnecessary to call Convert.ToInt32 if the only two possibilities are "1" and "0". If you are wanting to consider other cases, var isTrue = Convert.ToBoolean("true") == true && Convert.ToBoolean("1"); // Are both true. – TamusJRoyce Feb 08 '17 at 15:06
  • Look at Mohammad Sepahvand answer Michael Freidgeim comment! – TamusJRoyce Feb 08 '17 at 15:49
3

Here's my attempt at the most forgiving string to bool conversion that is still useful, basically keying off only the first character.

public static class StringHelpers
{
    /// <summary>
    /// Convert string to boolean, in a forgiving way.
    /// </summary>
    /// <param name="stringVal">String that should either be "True", "False", "Yes", "No", "T", "F", "Y", "N", "1", "0"</param>
    /// <returns>If the trimmed string is any of the legal values that can be construed as "true", it returns true; False otherwise;</returns>
    public static bool ToBoolFuzzy(this string stringVal)
    {
        string normalizedString = (stringVal?.Trim() ?? "false").ToLowerInvariant();
        bool result = (normalizedString.StartsWith("y") 
            || normalizedString.StartsWith("t")
            || normalizedString.StartsWith("1"));
        return result;
    }
}
Mark Meuer
  • 7,200
  • 6
  • 43
  • 64
3
    private static readonly ICollection<string> PositiveList = new Collection<string> { "Y", "Yes", "T", "True", "1", "OK" };

public static bool ToBoolean(this string input)
{
                return input != null && PositiveList.Any(λ => λ.Equals(input, StringComparison.OrdinalIgnoreCase));
}
1

I use this:

public static bool ToBoolean(this string input)
        {
            //Account for a string that does not need to be processed
            if (string.IsNullOrEmpty(input))
                return false;

            return (input.Trim().ToLower() == "true") || (input.Trim() == "1");
        }
Hoang Tran
  • 886
  • 3
  • 13
  • 32
0

I love extension methods and this is the one I use...

static class StringHelpers
{
    public static bool ToBoolean(this String input, out bool output)
    {
        //Set the default return value
        output = false;

        //Account for a string that does not need to be processed
        if (input == null || input.Length < 1)
            return false;

        if ((input.Trim().ToLower() == "true") || (input.Trim() == "1"))
            output = true;
        else if ((input.Trim().ToLower() == "false") || (input.Trim() == "0"))
            output = false;
        else
            return false;

        //Return success
        return true;
    }
}

Then to use it just do something like...

bool b;
bool myValue;
data = "1";
if (!data.ToBoolean(out b))
  throw new InvalidCastException("Could not cast to bool value from data '" + data + "'.");
else
  myValue = b;  //myValue is True
Arvo Bowen
  • 4,524
  • 6
  • 51
  • 109
0
string sample = "";

bool myBool = Convert.ToBoolean(sample);
Syscall
  • 19,327
  • 10
  • 37
  • 52
-1

If you want to test if a string is a valid Boolean without any thrown exceptions you can try this :

    string stringToBool1 = "true";
    string stringToBool2 = "1";
    bool value1;
    if(bool.TryParse(stringToBool1, out value1))
    {
        MessageBox.Show(stringToBool1 + " is Boolean");
    }
    else
    {
        MessageBox.Show(stringToBool1 + " is not Boolean");
    }

outputis Boolean and the output for stringToBool2 is : 'is not Boolean'

DisD
  • 11
  • 4