C# Boolean TryParse
Description
Boolean TryParse
tries to convert the specified string
representation of a logical value to its Boolean equivalent. A return value
indicates whether the conversion succeeded or failed.
Syntax
Boolean.TryParse
has the following syntax.
public static bool TryParse(
string value,
out bool result
)
Parameters
Boolean.TryParse
has the following parameters.
value
- A string containing the value to convert.result
- When this method returns, if the conversion succeeded, contains true if value is equal to Boolean.TrueString or false if value is equal to FalseString. If the conversion failed, contains false. The conversion fails if value is null or is not equal to the value of either the TrueString or FalseString field.
Returns
Boolean.TryParse
method returns true if value was converted successfully; otherwise, false.
Example
The following example calls the TryParse method to parse an array of strings.
using System;/* ww w. j av a 2s.c o m*/
public class Example
{
public static void Main()
{
string[] values = { "True", "False", "true", "false", " true ", "string" };
foreach (var value in values) {
bool flag;
if (Boolean.TryParse(value, out flag))
Console.WriteLine("'{0}' --> {1}", value, flag);
else
Console.WriteLine("Unable to parse '{0}'.",
value == null ? "<null>" : value);
}
}
}
The code above generates the following result.