How to determine whether the String represents a Numeric Type in C#

In this article we will discuss about how to determine whether the String represents a Numeric Type in C#
  • 2577

In this article we are discussing about how to determine whether the String represents a Numeric Type or not using TryParse() method in C#. This method takes two parameter. One parameter is the value which we want to convert and second parameter is the output variable in which the Boolean value will store. This method returns boolean value.

Lets have a look on the following example:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

 

namespace ConsoleApplication17

{

    class Program

    {

        static void Main(string[] args)

        {

            string numberstr = "1287543";

            long n1 = 0;

            bool canConvert = long.TryParse(numberstr, out n1);

            if (canConvert)

                Console.WriteLine("number1 = {0}", n1);

            else

                Console.WriteLine("numberstring is not a valid long");

 

            byte n2 = 0;

            numberstr = "255";

            canConvert = byte.TryParse(numberstr, out n2);

            if (canConvert)

                Console.WriteLine("number2 = {0}", n2);

            else

                Console.WriteLine("numberstring is not a valid byte");

 

            decimal n3 = 0;

            numberstr = "27.3";

            canConvert = decimal.TryParse(numberstr, out n3);

            if (canConvert)

                Console.WriteLine("number3 = {0}", n3);

            else

                Console.WriteLine("numberstring is not a valid decimal");

            System.Console.ReadLine();

 

        }

    }

}

 

Output:

Image28.jpg

Ask Your Question

Got a programming related question? You may want to post your question here

Programming Answers here

Categories

More Articles

© 2020 DotNetHeaven. All rights reserved.