Advertisement
Beginner C# Programming, Strings in C#

How do you determine whether a String represents a numeric value?

Short answer

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.

Save C# Programming mock interview
Advertisement
AModel answer
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.
Likely follow-ups
  • What is the difference between int.Parse and int.TryParse methods?
  • Are there similar TryParse methods for other data types like dates?
Related topics