88

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.

6
  • 5
    var result = Convert.ToBoolean("mystring") Mar 31, 2018 at 17:57
  • more general bool thevalue = ("thisistrue"==mystring); Mar 31, 2018 at 18:01
  • bool.TryParse("your string", out bool result); // returns True or False
    – Saeid
    Feb 9 at 8:04
  • What is "TopMost"? E.g., is it literal? May 21 at 16:03
  • OK, the OP has left the building: "Last seen more than 4 years ago". Perhaps somebody else can chime it? May 21 at 16:05

3 Answers 3

190

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

1
  • 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, 2021 at 23:03
23

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();
6
  • AFAIK your second function is not very useful :( .. But appreciate our answer :) Mar 31, 2018 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, 2018 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 :) Mar 31, 2018 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, 2018 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 ? Mar 31, 2018 at 18:32
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.