How to convert string to bool
string yes no convert into bool true and false
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
VulpesRank #55 · 29.2K reputationPosted Jan 11, 2015, 5:46 AM EST
string yn = "yes" ; // or "no"
bool b = (yn.ToLower() == "yes");
Armin Hafizovic4 reputationPosted Jan 11, 2015, 5:57 AM EST
string value = "YES"; // or NO
bool result = value.equals("YES", StringComparison.Ordinal);
You could also have an enumeration for your values that you will compare a value against which makes your program more flexible, but for just getting a boolean value depending on the result, this code works just fine.
theLizardRank #1,079 · 1.8K reputationPosted Jan 11, 2015, 10:15 AM EST
String value = "Yes"
bool result = (value.ToLower()=="yes" ? true:false);
or you could create a methode that you could reuse use at will
bool myBoolMethod(String a, string b, bool wantTrueFalse)
{
//compare two strings
bool result;
a = a.ToLower();
b = b.ToLower()
if(wantTrueFalse)
result = (a == b? True : False);
else
result = (a == b? 1 : 0);
}
bool myBoolMethod(String a, bool wantTrueFalse)
{
bool result;
a = a.ToLower();
if(wantTrueFalse)
result = (a == "yes"? True : False);
else
result = (a == "yes"? 1 : 0);
}
String MySurname = "Fred", hisSurname = " Smith"
then you can do bool myanswer = myBoolMethod(MySurname, hisSurname, true);
on return myanswer will be False.
VulpesRank #55 · 29.2K reputationPosted Jan 11, 2015, 12:24 PM EST
http://msdn.microsoft.com/en-us/library/system.boolean.tryparse%28v=vs.110%29.aspx
Here's the code to do that for 'Yes' and 'No' values, ignoring case and leading/trailing whitespace:
Yi Rong Tan50 reputationPosted Jan 11, 2015, 8:37 PM EST
//Let yesNoString be the string containing the "yes" or "no" value
//Let yesNoBoolean be the boolean to be converted to.
if(yesNoString = "yes")
{
YesNoBoolean = true;
}
else if(yesNoString = "no")
{
yesNoBoolean = false;
}