Reputation: 16003
You would think there would be a way using DirectCast, TryCast, CType etc but all of them seem to choke on it e.g.:
CType("Yes", Boolean)
You get:
System.InvalidCastException - Conversion from string "Yes" to type 'Boolean' is not valid.
Upvotes: 21
Views: 37287
Reputation: 20811
I like switch
for this since it's simple and easily scales as needed. The default pattern catches empty strings and nulls without any fuss. I also like extension methods, so I end up with this:
public static class StringExtensions
{
public static bool ToBool(this string str)
{
return str?.ToLower() switch
{
"true" => true,
"yes" => true,
"y" => true,
"t" => true,
"1" => true,
_ => false
};
}
}
Usage
"Yes".ToBool(); // true
"no".ToBool(); // false
"".ToBool(); // false
string s = null;
s.ToBool(); // false
Upvotes: 2
Reputation: 146
public static bool IsBoolean(string strValue)
{
return !string.IsNullOrEmpty(strValue) && ("1/YES/TRUE".IndexOf(strValue, StringComparison.CurrentCultureIgnoreCase) >= 0);
}
Upvotes: 0
Reputation: 6694
No, but you could do something like:
bool yes = "Yes".Equals(yourString);
Upvotes: 20
Reputation: 6164
I like the answer that @thelost posted, but I'm reading values from an ADO.Net DataTable and the casing of the string in the DataTable can vary.
The value I need to get as a boolean is in a DataTable named childAccounts
in a column named Trades
.
I implemented a solution like this:
bool tradeFlag = childAccounts["Trade"].ToString().Equals("yes", StringComparison.InvariantCultureIgnoreCase);
Upvotes: 0
Reputation: 63
C# 6+ version:
public static bool StringToBool(string value) =>
value.Equals("yes", StringComparison.CurrentCultureIgnoreCase) ||
value.Equals(bool.TrueString, StringComparison.CurrentCultureIgnoreCase) ||
value.Equals("1");`
Upvotes: 5
Reputation: 1
private bool StrToBool(string value)
{ // could be yes/no, Yes/No, true/false, True/False, 1/0
bool b = false;
if (value.Equals("yes", StringComparison.CurrentCultureIgnoreCase) || value.Equals(Boolean.TrueString, StringComparison.CurrentCultureIgnoreCase) || value.Equals("1"))
{
b = true;
}
else if (value.Equals("no", StringComparison.CurrentCultureIgnoreCase) || value.Equals(Boolean.FalseString, StringComparison.CurrentCultureIgnoreCase) || value.Equals("0"))
{
b = false;
}
else
{ // we should't be here
b = false;
}
return b;
}
Upvotes: 0
Reputation: 1
Here is a simple way to get this done.
rv.Complete = If(reader("Complete") = "Yes", True, False)
Upvotes: -1
Reputation: 1
Public Function TrueFalseToYesNo(thisValue As Boolean) As String
Try
If thisValue Then
Return "Yes"
Else
Return "No"
End If
Catch ex As Exception
Return thisValue.ToString
End Try
End Function
Upvotes: -2
Reputation: 9094
private static bool GetBool(string condition)
{
return condition.ToLower() == "yes";
}
GetBool("Yes"); // true
GetBool("No"); // false
Or another approach using extension methods
public static bool ToBoolean(this string str)
{
return str.ToLower() == "yes";
}
bool answer = "Yes".ToBoolean(); // true
bool answer = "AnythingOtherThanYes".ToBoolean(); // false
Upvotes: 4
Reputation: 12658
You Can't. But you should use it as
bool result = yourstring.ToLower() == "yes";
Upvotes: 2
Reputation: 5602
Slightly off topic, but I needed once for one of my classes to display 'Yes/No' instead of 'True/False' in a property grid, so I've implemented YesNoBooleanConverter
derived from BooleanConverter
and decorating my property with <TypeConverter(GetType(YesNoBooleanConverter))> _
...
Upvotes: 2
Reputation: 3207
Using this way, you can define conversions from any string you like, to the boolean value you need. 1 is true, 0 is false, obviously.
Benefits: Easily modified. You can add new aliases or remove them very easily.
Cons: Will probably take longer than a simple if. (But if you have multiple alises, it will get hairy)
enum BooleanAliases { Yes = 1, Aye = 1, Cool = 1, Naw = 0, No = 0 } static bool FromString(string str) { return Convert.ToBoolean(Enum.Parse(typeof(BooleanAliases), str)); } // FromString("Yes") = true // FromString("No") = false // FromString("Cool") = true
Upvotes: 31
Reputation: 49984
If you think about it, "yes" cannot be converted to bool because it is a language and context specific string.
"Yes" is not synonymous with true (especially when your wife says it...!). For things like that you need to convert it yourself; "yes" means "true", "mmmm yeeessss" means "half true, half false, maybe", etc.
Upvotes: 86