Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to validate a string for a numeric representation using TryParse in C#
The TryParse method in C# is used to validate whether a string contains a valid numeric representation. It attempts to convert the string to a number and returns true if successful, or false if the conversion fails. This is safer than using Parse because it doesn't throw exceptions on invalid input.
Syntax
Following is the syntax for using TryParse −
bool result = int.TryParse(stringValue, out int number);
Parameters
-
stringValue − The string to be parsed.
-
out number − The output parameter that receives the parsed value if successful, or zero if parsing fails.
Return Value
Returns true if the string was successfully converted to a number; otherwise, false.
Using TryParse for Integer Validation
Example
using System;
class Program {
static void Main() {
bool res;
int a;
string myStr = "5";
// checking for valid string representation of a number
res = int.TryParse(myStr, out a);
Console.WriteLine("String: " + myStr);
Console.WriteLine("Is valid integer: " + res);
Console.WriteLine("Parsed value: " + a);
}
}
The output of the above code is −
String: 5 Is valid integer: True Parsed value: 5
Using TryParse with Invalid Strings
Example
using System;
class Program {
static void Main() {
string[] testStrings = {"123", "abc", "45.67", "", "2147483648"};
foreach (string str in testStrings) {
bool isValid = int.TryParse(str, out int result);
Console.WriteLine($"'{str}' -> Valid: {isValid}, Value: {result}");
}
}
}
The output of the above code is −
'123' -> Valid: True, Value: 123 'abc' -> Valid: False, Value: 0 '45.67' -> Valid: False, Value: 0 '' -> Valid: False, Value: 0 '2147483648' -> Valid: False, Value: 0
Using TryParse with Different Data Types
Example
using System;
class Program {
static void Main() {
string doubleStr = "123.45";
string longStr = "9876543210";
// Double validation
if (double.TryParse(doubleStr, out double doubleValue)) {
Console.WriteLine($"Valid double: {doubleValue}");
}
// Long validation
if (long.TryParse(longStr, out long longValue)) {
Console.WriteLine($"Valid long: {longValue}");
}
// Boolean validation
string boolStr = "true";
if (bool.TryParse(boolStr, out bool boolValue)) {
Console.WriteLine($"Valid boolean: {boolValue}");
}
}
}
The output of the above code is −
Valid double: 123.45 Valid long: 9876543210 Valid boolean: True
Common Use Cases
-
User Input Validation − Validating numeric input from users before processing.
-
File Processing − Parsing numeric data from text files or CSV files.
-
Configuration Reading − Converting string configuration values to numbers safely.
-
Data Conversion − Converting strings from databases or APIs to numeric types.
Conclusion
The TryParse method provides a safe way to validate and convert strings to numeric types without throwing exceptions. It returns true for successful conversions and false for invalid input, making it ideal for input validation and data processing scenarios.
