Saturday 1 November 2014

Converting String to Int in C#

String is the reference type in C# and int is the value type.(What is Ref and Value type )
So, The way of maintain the memory location are quite different for both of them and to converting the value to refrence is called boxing in C#.

If you see the below program;
static void Main(string[] args)
        {
            int i = 123;
            string str = "123";

            if (str.Equals(i))
                Console.WriteLine("Success");
            else
                Console.WriteLine("fails");

        }


O/p : Fails;

You  will get the o/p as Fails; because we are comparing the value type with reference type, So the both  of them are different for maintain the values.


Now, how to convert the string to Int.

C# providing many ways to convert the value string to Int type;
We can use the try parse which is as the static method.
class Program
    {
        static void Main(string[] args)
        {
            int i;
            string str = "123";

            //Parsing/converting string to Integer
            int.TryParse(str,out i);

            // Chcking both is havng same value or not
            if (i == 123)
                Console.WriteLine("Success");
            else
                Console.WriteLine("fails");

        }
    }

O/p : Success;

We can use Convert.toInt32, it will also convert the string to integer type.
static void Main(string[] args)
        {
            int i;
            string str = "123";

            //Parsing/converting string to Integer
            i = Convert.ToInt32(str);

            // Chcking both is havng same value or not
            if (i == 123)
                Console.WriteLine("Success");
            else
                Console.WriteLine("fails");

        }
O/p : Success;





No comments:

Post a Comment