In C#, Char.TryParse attempts to convert a string to a char. It returns true only when the string has exactly one character.
On failure it returns false and sets the out value to a default char—no exception. Prefer TryParse over Parse for user input.
This is a static member of System.Char. You call it with the type name, such as Char.TryParse(...) or char.TryParse(...). A char holds one 16-bit UTF-16 code unit.
Syntax
Pass the string and an out char variable.
C#
if (Char.TryParse(text, out char c)) {
Console.WriteLine(c);
}
Call
What it does
Char.TryParse(s, out c)
True when s has length 1; c receives the char.
Empty, null, or multi-character strings return false.
Library declarations
C#
public static bool TryParse(string s, out char result);
Parameters
Parameter
Description
s
String to parse.
result
Out parameter receiving the char when successful.
Return Value
Return Value
Description
true
Parsed successfully.
false
Not a length-1 string.
C# Examples
Example 1 — Parse "Z" Safely
Succeed with a one-character string.
C#
using System;
class Program {
static void Main() {
if (Char.TryParse("Z", out char c)) {
Console.WriteLine("ok: " + c);
} else {
Console.WriteLine("fail");
}
}
}
Output
ok: Z
How It Works
Length one. "Z" is valid.
Out char. c receives Z.
True branch. Prints ok.
No throw. Failure would take the else path instead.
Example 2 — Reject Longer Text
Show false for a two-character string.
C#
using System;
class Program {
static void Main() {
bool ok = Char.TryParse("Hi", out char c);
Console.WriteLine(ok);
Console.WriteLine("result default?: " + (c == '\0'));
}
}
Output
False
result default?: True
How It Works
Length two. "Hi" cannot be one char.
False return. Parse failed safely.
Default out. Often '\0' on failure.
Do not use c. Ignore out value when ok is false.
Example 3 — Accept Single Char Codes
Accept only single-character codes from a list.
C#
using System;
class Program {
static void Main() {
string[] samples = { "A", "BC", "" };
foreach (string s in samples) {
bool ok = Char.TryParse(s, out char c);
Console.WriteLine((s == "" ? "(empty)" : s) + " -> " + ok + (ok ? (" (" + c + ")") : ""));
}
}
}