Tuesday, August 20, 2013

C# - Casting Variables

Casting Review

In C# we have many variables that we can use, in some situations, we need to “Convert” variable of type A, into variable from type B. To  accomplish this transformation we need to use a“Cast” operation.

Example:

Class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Please insert your age");
            string clientage = Console.ReadLine();
            example(clientage);//Failure
        }

        static void example(int clientage)
        {
            Console.WriteLine(clientage += 10);
        } 
    }

After Cast:

class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Please insert your age");
            string clientage = Console.ReadLine();

            //Casting from string INTO integer

            int CastingFromStringtoInt = int.Parse(clientage);

            example(CastingFromStringtoInt);//Pass
        }

        static void example(int clientage)
        {
            Console.WriteLine(clientage += 10);
        } 
    }

Casting examples
The following examples will demonstrate how to create cast in different ways

Casting any variable into string:
Casting to string is really simple, all we need to do is to use the ‘To String’ method

class Program
    {
        static void Main(string[] args)
        {
            int A = 10;
            bool B = true;

              //Cast 1 :

            string d = A.ToString();

            //Cast 2 :

            d = B.ToString();
        }
    }

Casting string into different variable:

This example demonstrates how can you convert a string into another variable in two different ways

Note!

If the string variable contains any char that is different from a number, the cast will fail with casting error.  

class Program
    {
        static void Main(string[] args)
        {
          string a = "3";
          int Cast_1 = int.Parse(a);

          double Cast_2 = Convert.ToDouble(a);
        }
    }

No comments:

Post a Comment

My Presentations