'Convert string to boolean in C#

I need help converting a string to a bool 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.



Solution 1:[1]

You must use some of the C # conversion systems:

string to boolean: True to true

string str = "True";
bool mybool = System.Convert.ToBoolean(str);

boolean to string: true to True

bool mybool = true;
string str = System.Convert.ToString(mybool);

//or

string str = mybool.ToString();

bool.Parse expects one parameter which in this case is str, even .

Convert.ToBoolean expects one parameter.

bool.TryParse expects two parameters, one entry (str) and one out (result).

If TryParse is true, then the conversion was correct, otherwise an error occurred

string str = "True";
bool MyBool = bool.Parse(str);

//Or

string str = "True";
if(bool.TryParse(str, out bool result))
{
   //Correct conversion
}
else
{
     //Incorrect, an error has occurred
}

Solution 2:[2]

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.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Patrick Knott