EN
C# / .NET - convert string to bool
9 points
In C#/.NET string can be parsed to bool in few ways.
xxxxxxxxxx
1
string text = "True";
2
bool value = bool.Parse(text);
3
Console.WriteLine(value);
Output:
xxxxxxxxxx
1
True
xxxxxxxxxx
1
string text = "True";
2
bool value;
3
4
if (bool.TryParse(text, out value))
5
Console.WriteLine(value);
Output:
xxxxxxxxxx
1
True
xxxxxxxxxx
1
string text = "True";
2
bool value = Convert.ToBoolean(text);
3
Console.WriteLine(value);
Output:
xxxxxxxxxx
1
True
xxxxxxxxxx
1
TypeConverter converter = TypeDescriptor.GetConverter(typeof(bool));
2
3
string text = "True";
4
bool value = (bool)converter.ConvertFrom(text);
5
6
Console.WriteLine(value);
Output:
xxxxxxxxxx
1
True
xxxxxxxxxx
1
string text = "True";
2
bool value = (text == "True");
3
Console.WriteLine(value);
Output:
xxxxxxxxxx
1
True
The following methodsbool.Parse
,bool.TryParse
,Convert.ToBoolean
andTypeConverter.ConvertFrom
throw System.FormatException.