C# | Char.TryParse () Method
Last Updated :
10 Feb, 2023
In C#, Char.TryParse() is Char class method which is used to convert the value from given string to its equivalent Unicode character. Its performance is better than Char.Parse() method. Syntax :
public static bool TryParse(string str, out char result)
Parameter:
- str: It is System.String type parameter which can contain single character or NULL.
- result: This is an uninitialized parameter which is used to store the Unicode character equivalent when the conversion succeeded, or an undefined value if the conversion failed. The type of this parameter is System.Char.
Return Type: The method return True, if successfully converted the string, otherwise return False. So type of this method is System.Boolean. Note: When string is NULL or Length is equal to 1 then conversion failed.
Example 1: Below is a program to demonstrates the use of Char.TryParse() Method .
CSHARP
using System;
class GFG {
static public void Main()
{
bool result;
Char value;
result = Char.TryParse("A", out value);
Console.WriteLine(result);
Console.WriteLine(value.ToString());
result = Char.TryParse("Z", out value);
Console.WriteLine(result);
Console.WriteLine(value.ToString());
result = Char.TryParse("$", out value);
Console.WriteLine(result);
Console.WriteLine(value.ToString());
result = Char.TryParse("100", out value);
Console.WriteLine(result);
Console.WriteLine(value.ToString());
result = Char.TryParse("z", out value);
Console.WriteLine(result);
Console.WriteLine(value.ToString());
}
}
|
Output:
True
A
True
Z
True
$
False
True
z
Example 2: Below is an program to demonstrates the use Char.TryParse() method where the input is not a single character and start with a symbol.
CSHARP
using System;
class GFG {
static public void Main()
{
bool result;
Char value;
result = Char.TryParse("GeeksforGeeks", out value);
Console.WriteLine(result);
Console.WriteLine(value.ToString());
result = Char.TryParse("<N", out value);
Console.WriteLine(result);
Console.WriteLine(value.ToString());
}
}
|
Share your thoughts in the comments
Please Login to comment...