65.9K
CodeProject is changing. Read more.
Home

Validating Simple Primitive Data Types :TIP (For beginners)

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.46/5 (12 votes)

Oct 24, 2010

CPOL
viewsIcon

29621

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...