Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / programming

Validating Simple Primitive Data Types :TIP (For beginners)

4.46/5 (13 votes)
13 Nov 2010CPOL 29.6K  
Validating Simple Primitive Data Types:TIP

Introduction



In general, most of the developers are not aware of the inbuilt methods available for validating the primitive data types like System.Int32 and end up doing a custom implementation. The function below is a sample of that custom implementation to validate whether the given string is numeric or not.

public bool CheckIfNumeric(string value)
  {
      bool isNumeric = true;
      try
      {
          int i = Convert.ToInt32(value);
      }
      catch(FormatException exception)
      {
          isNumeric = false;
      }
      return isNumeric;
  }


Since it involves try catch, it is not the best way. A better approach would be to use int.TryParse as shown below:

int output = 0;
  bool isNumeric = int.TryParse(value, out output);


int.TryParse, in my opinion, is definitely the faster and cleaner way.

Keep a watch for more...

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)