Validate string is number or not in C#

By

Validate String is number or not in C#
Dear Code  Can you provide me code for check the given string is number or not? I am asking these because some time i have to validate if given input is numeric then go for next step .

Dear Topic yes sure i will provide a solution for this .Use TryParse method. TryParse is return bool value.If it return true then the given input is numeric otherwise its string .Before going for example lets talk about how many argument its takes.It takes two argument  first argument is string or number which have to check and second one is out parameter which have the value of this if it is number.

Code Sample [C# Code]

using System;

public class Program
{
    public static void Main()
    {
        string strInput = "";
        Console.WriteLine("Enter the input which you have to check.");
        strInput = Console.ReadLine();
        int Num;
        bool isNumeric = int.TryParse(strInput, out Num);
        if (isNumeric)
            Console.WriteLine("Enter input is a number and number is."+Num.ToString());
        else
            Console.WriteLine("Enter input is not a number.");
    }

}

Output
Enter the input which you have to check.
input is-  My test
output is- Enter input is not a number.

Enter the input which you have to check.
input is-  123
output is- Enter input is a number and number is. 123

Explanation
Here I am using TryParse  method.In above example i write int.TryParse you can also use double.TryParse.but when you use double.TryParse then you have to declare double for out parameter.Beside TryParse if we use only Parse method then if its not numeric then it throw error .So better is use TryParse mwthod instead of only Parse method.


0 comments:

Post a Comment