Convert string to boolean in C#

Convert string to boolean in C#

I know this is not an ideal question to answer but as the OP seems to be a beginner, Id love to share some basic knowledge with him… Hope everybody understands

OP, 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 doesnt 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

Hope you understand 🙂

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);


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);


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

Convert string to boolean in C#

Leave a Reply

Your email address will not be published. Required fields are marked *