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:
// C# program to demonstrate // Boolean.TryParse(String, Boolean) // Method using System; class GFG { // Main Method public static void Main() { // passing different values // to the method to check checkParse( "true" ); checkParse( "false" ); checkParse( "' true '" ); checkParse( " $ " ); checkParse( "1" ); } // Declaring checkparse method public static void checkParse( string value) { // Declaring data type bool result; bool flag; // using the method result = Boolean.TryParse(value, out flag); // Display boolean type result Console.WriteLine( "{0} --> {1} " , value, result); } } |
true --> True false --> True ' true ' --> False $ --> False 1 --> False
Example 2:
// C# program to demonstrate // Boolean.TryParse(String, Boolean) // Method using System; class GFG { // Main Method public static void Main() { // passing different values // to the method to check checkParse( "true1" ); checkParse( null ); checkParse(String.Empty); } // Declaring checkparse method public static void checkParse( string value) { // Declaring data type bool result; bool flag; // using the method result = Boolean.TryParse(value, out flag); // Display boolean type result Console.WriteLine( "{0} --> {1} " , value, result); } } |
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:
- https://docs.microsoft.com/en-us/dotnet/api/system.boolean.tryparse?view=netframework-4.7.2