C# Programming › Strings in C#
How do you determine whether a String represents a numeric value?
BeginnerAnswer
You can determine whether a string represents a numeric value by using methods like int.TryParse, double.TryParse, or decimal.TryParse, which attempt to convert the string and return a boolean indicating success or failure without throwing an exception if the conversion fails. This approach is much safer than trying to parse the string directly and catching an exception, since exceptions are relatively expensive and checking with TryParse is both faster and cleaner.
string input = "123";
if (int.TryParse(input, out int number)) {
Console.WriteLine($"Valid number: {number}");
} else {
Console.WriteLine("Not a valid number");
}Real-world example A form that accepts a user's age as text input uses int.TryParse to safely validate the entered value before saving it, immediately showing a friendly error message if the user typed letters instead of digits.