CopyPastehas never been so tasty!

Convert String into Integer using TryParse Method in C#

by anonymous

  • 0
  • 0
  • 0
80 views

Orignal Source:http://codingvilla.com/convert-string-to-integer-csharp-single-article-604.aspx

 

TryParse Method:

 

int.TryParse used to convert string into int. It does not throw exception on null value. To check that exception we use if else.

 

Out Keyword:

 

The out keyword makes our program reliable because sometimes a function returns more than one value to handle this problem we use out keyword because it saves a new copy of that variable. Using this we can check that our variable is valid or invalid. 

 

Convert String into Integer using TryParse Method

 

To convert String into Integer using TryParse Method we write a method TryToParse. We use the Int32 Structure and call the method Try parse, and the first parameter must be a string and second parameter must be ‘out’ parameter.

 

To demonstrate make a console application and write the following code.

 

Code:

 

classStringToInteger

    {

staticvoid Main(string[] args)

        {

            TryToParse(null);

            TryToParse("160519");

            TryToParse("9432.0");

            TryToParse("16,667");

            TryToParse("   -322   ");

            TryToParse("+4302");

            TryToParse("(100);");

            TryToParse("01FA");

Console.ReadLine();

 

        }

privatestaticvoid TryToParse(string value)

        {

int number;

bool result = Int32.TryParse(value, out number);

if (result)

            {

Console.WriteLine("Converted '{0}' to {1}.", value, number);

            }

else

            {

if (value == null) value = "";

Console.WriteLine("Attempted conversion of '{0}' failed.", value);

            }

        }

    }

 

Add A Comment: