83

I need help converting a string to a Boolean value:

I've been trying to get the value (true or false) from the TopMost for my program and save it in my settings.

Settings1.Default["tm"] = ;
Settings1.Default.Save();

The type for my setting 'tm' is a bool value (true, false), but I've only been using C# for a short amount of time and I'm not sure how to save whether or not my TopMost will be true or false.

Before you say to use the one in properties, it's a user option; I want them to be able to choose the option of whether it's on (true) or off (false), but have it save and load as a bool value.

Daniel Mann
  • 57,011
  • 13
  • 100
  • 120

3 Answers3

182

You can convert a string to type Boolean by using any of the methods stated below:

 string sample = "True";
 bool myBool = bool.Parse(sample);

 // Or

 bool myBool = Convert.ToBoolean(sample);

bool.Parse expects one parameter which in this case is sample, .ToBoolean also expects one parameter.

You can use TryParse which is the same as Parse, but it doesn't throw any exception :)

string sample = "false";
Boolean myBool;

if (Boolean.TryParse(sample , out myBool))
{
    // Do Something
}

Please note that you cannot convert any type of string to type Boolean because the value of a Boolean can only be True or False

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Software Dev
  • 5,368
  • 5
  • 22
  • 45
  • 10
    Note that the argument to `bool.Parse` is not case specific. The following test cases will all pass: `Assert.IsTrue(bool.Parse("True")); Assert.IsTrue(bool.Parse("TRUE")); Assert.IsTrue(bool.Parse("true"));` – Mark D Oct 22 '21 at 23:03
22

C# offers several ways to convert a string value to a boolean value. I will proceed to explain some of them below:

bool.Parse(string value) or System.Convert.ToBoolean(string value)

Both methods are quite similar in that they both take a string as their input value and return the boolean representation of that string as their output value. Note that both will throw a FormatException if the input string does not represent a boolean, whereas if the input string is null, bool.Parse will throw an ArgumentNullException while System.Convert.ToBoolean just returns false.

// Valid, also TRUE, FALSE, true, false, trUE, FAlse, etc. (case insensitive)
bool result = bool.Parse("True");
bool result = System.Convert.ToBoolean("False");

// Invalid
bool result = bool.Parse(null);
bool result = System.Convert.ToBoolean("thisIsNotABoolean");

bool.TryParse(string value, out bool result)

Similar to bool.Parse except that it doesn't throw any exceptions directly, instead it returns a boolean value indicating whether or not the conversion could be performed. Also, the converted value now appears in an out bool result output parameter instead of being returned by the function.

bool success = bool.TryParse("True",  out bool result); // success: True
bool success = bool.TryParse("False", out bool result); // success: True
bool success = bool.TryParse(null,    out bool result); // success: False
bool success = bool.TryParse("thisIsNotABoolean", out bool result); // success: False

string.Equals(string value)

This is not exactly a direct conversion method and I personally prefer any of the above, but if for some reason you don't have access to them, you can use this alternative.

bool result = "True" .Equals("true", StringComparison.OrdinalIgnoreCase); // True
bool result = "False".Equals("true", StringComparison.OrdinalIgnoreCase); // False

StringExtensions

Depending on what you want to achieve, an extension method might be a good option.

public static class StringExtensions
{
    public static bool ToBoolean(this string value)
    {
        if (bool.TryParse(value, out bool result))
        {
            return result;
        }

        return false;
    }
}

Then

bool result = "True".ToBoolean();
Héctor M.
  • 2,302
  • 4
  • 17
  • 35
  • AFAIK your second function is not very useful :( .. But appreciate our answer :) – Software Dev Mar 31 '18 at 18:24
  • 1
    In your post, the correct form is Convert.ToBoolean, not Convert.ToBool since the ToBool method does not exist – Héctor M. Mar 31 '18 at 18:27
  • See,that's what i love about programmers, they point out each other's flaws and help to improve...Thank you so much mate :) – Software Dev Mar 31 '18 at 18:28
  • @zackraiyan And if you really appreciate my answer, would you consider giving it a vote? The second option is a generic form of conversion from string to bool, if "True" == "True" or if "False" == "False" – Héctor M. Mar 31 '18 at 18:29
  • But the second method is still not an ideal one to check :( because then you need two strings to compare .... However,i won't upvote because your answer doesn't contain any explanation :( ... It's not like that i don't want to upvote, i am willing to ... But i cannot let any answer be at the top which has no information of what's happening .... You can edit your answer, right ? – Software Dev Mar 31 '18 at 18:32
  • TryPares() is the best. Thanks – Saeid Feb 09 '23 at 08:03
3

If you just don't care about what to do when it fails, use this extension:

    public static bool GetBool(this string input)
    {
        var boolResult = false;
        bool.TryParse(input, out boolResult);
        return boolResult;
    }

If it isn't True, true, it is false. No exceptions.

Patrick Knott
  • 1,666
  • 15
  • 15