C# | Boolean.TryParse() Method
This method is used to convert the specified string representation of a logical value to its Boolean equivalent. It returns a value that indicates whether the conversion succeeded or failed.
Syntax:
public static bool TryParse (string value, out bool result);
Parameters:
value: It is a string containing the value to convert.
result: When this method returns, if the conversion succeeded, contains true if value is equal to TrueString or false if value is equal to FalseString. If the conversion failed, contains false. The conversion fails if the value is null or is not equal to the value of either the TrueString or FalseString field.
Return Value: This method returns true if value was converted successfully otherwise it returns false.
Below programs illustrate the use of Boolean.TryParse(String, Boolean) Method:
Example 1:
using System;
class GFG {
public static void Main() {
checkParse( "true" );
checkParse( "false" );
checkParse( "' true '" );
checkParse( " $ " );
checkParse( "1" );
}
public static void checkParse( string value) {
bool result;
bool flag;
result = Boolean.TryParse(value, out flag);
Console.WriteLine( "{0} --> {1} " , value, result);
}
}
|
Output:
true --> True
false --> True
' true ' --> False
$ --> False
1 --> False
Example 2:
using System;
class GFG {
public static void Main()
{
checkParse( "true1" );
checkParse( null );
checkParse(String.Empty);
}
public static void checkParse( string value) {
bool result;
bool flag;
result = Boolean.TryParse(value, out flag);
Console.WriteLine( "{0} --> {1} " , value, result);
}
}
|
Output:
true1 --> False
--> False
--> False
Note: The TryParse method is like the Parse method, except the TryParse method does not throw an exception if the conversion fails.
Reference:
Last Updated :
20 Apr, 2019
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...