- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to validate whether a string is a number in C#?
A string having number can be validated using int.TryParse or int.Parse.
Int.Parse throws an exception if it cannot parse the string to an integer, whereas Int.TryParse returns a bool indicating whether it succeeded. Also, Int.TryParse has an out parameter which has the value of the parsed string.
Example
using System; namespace DemoApplication { class Program { static void Main(string[] args) { string numberString = "123"; int number = 0; if(int.TryParse(numberString, out number)) { Console.WriteLine($"Try Parse Interger Number: {number}"); } Console.WriteLine($"Parse Interger Number: {int.Parse(numberString)}"); Console.ReadLine(); } } }
Output
The output of the code is
Try Parse Interger Number: 123 Parse Interger Number: 123
In the above example since int.Tryparse returns a boolean value along with the parsed string in the out parameter, the if condition returns true. Also, int.Parse return the integer value as the string contains a proper number.
Example
using System; namespace DemoApplication { class Program { static void Main(string[] args) { string numberString = "A123"; int number = 0; if(int.TryParse(numberString, out number)) { Console.WriteLine($"Try Parse Interger Number: {number}"); } elsem{ Console.WriteLine($"String doesnot have a proper number"); } Console.ReadLine(); } } }
Output
The output of the above code is
String doesnot have a proper number
As the string does not have a proper number, the int.Tryparse will return false and the else part of the code is executed. In the same case, int.Parse will throw exception like below.
Example
using System; namespace DemoApplication { class Program { static void Main(string[] args) { string numberString = "A123"; Console.WriteLine($"Parse Interger Number: {int.Parse(numberString)}"); //Exception: Input string was not in correct format. } } }