C# | Boolean.Parse() Method
Last Updated :
13 Sep, 2021
This method is used to convert the specified string representation of a logical value to its Boolean equivalent.
Syntax:
public static bool Parse (string value);
Here, the value is the string which contains the value to convert.
Return Value: This method returns true if value is equivalent to TrueString false if value is equivalent to FalseString.
Exceptions:
- ArgumentNullException: If the string value is null.
- FormatException: If the value is not equivalent to TrueString or FalseString.
Below programs illustrate the use of Boolean.Parse(String) Method:
Example 1:
CSHARP
using System;
class GFG {
public static void Main()
{
try {
checkParse( "true" );
checkParse( "TRUE" );
checkParse( "false" );
checkParse( "FALSE" );
checkParse( bool .TrueString);
checkParse( bool .FalseString);
}
catch (ArgumentNullException e) {
Console.Write( "Exception Thrown: " );
Console.Write( "{0}" , e.GetType(), e.Message);
}
catch (FormatException e) {
Console.Write( "Exception Thrown: " );
Console.Write( "{0}" , e.GetType(), e.Message);
}
}
public static void checkParse( string input)
{
bool val;
val = bool .Parse(input);
Console.WriteLine( "'{0}' parsed as {1}" , input, val);
}
}
|
Output:
'true' parsed as True
'TRUE' parsed as True
'false' parsed as False
'FALSE' parsed as False
'True' parsed as True
'False' parsed as False
Example 2: For ArgumentNullException
CSHARP
using System;
class GFG {
public static void Main()
{
try {
checkParse( null );
}
catch (ArgumentNullException e) {
Console.Write( "Exception Thrown: " );
Console.Write( "{0}" , e.GetType(), e.Message);
}
catch (FormatException e) {
Console.Write( "Exception Thrown: " );
Console.Write( "{0}" , e.GetType(), e.Message);
}
}
public static void checkParse( string input)
{
bool val;
val = bool .Parse(input);
Console.WriteLine( "'{0}' parsed as {1}" , input, val);
}
}
|
Output:
Exception Thrown: System.ArgumentNullException
Example 3: For FormatException
CSharp
using System;
class GFG {
public
static void Main()
{
try {
checkParse( "true" );
}
catch (ArgumentNullException e) {
Console.Write( "Exception Thrown: " );
Console.Write( "{0}" , e.GetType(), e.Message);
}
catch (FormatException e) {
Console.Write( "Exception Thrown: " );
Console.Write( "{0}" , e.GetType(), e.Message);
}
}
public static void checkParse( string input)
{
bool val;
val = bool .Parse(input);
Console.WriteLine( "'{0}' parsed as {1}" , input, val);
}
}
|
Output:
Exception Thrown: System.FormatException
Note: The value parameter, optionally preceded or trailed by white space, must contain either TrueString or FalseString otherwise, it will throw an exception and the comparison is case-insensitive.
Reference:
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...