Validating Simple Primitive Data Types :TIP (For beginners)
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 likeSystem.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...