Pages

Thursday, April 26, 2012

Typecasting
Author: Suresh Konjerla
In this article I am going to explain the concept of type casting. Typecasting is concept of converting data from one data type to another data type. C# supports 2 types of type Casting. Those are
1)      Implicit Type Casting
2)      Explicit Type Casting    

C# supports 4 types of Type casting techniques
1)      C++ style of typecasting
2)      Converting
3)      Parsing
4)      Boxing and UnBoxing

Now I am going to explain 1 & 2 types of Type casting techniques here

1)    C++ Style of typecasting :

Syntax:  datatype1 var1 = value;
Datatype2 var2 = (Datatype2) var1;
     Example program:
2)    Converting  :
     Converting is used to type cast data from any data type to another data type.
Working with predefined class called Convert is Converting. Convert Class collection of static methods used for type casting. Those are

è      ToByte(value)     : used to convert data  into Byte data type
è      ToString(value )  : used to convert data into String data type
è      ToBoolean(value): used to convert data into Boolean data type
è      ToChar(value)     : used to convert data into char data type
è      ToInt32(value)    : used to convert data into integer data type
è      To Double(value) : used to convert data into Double data type
          
Example:

    double d = 10.1;
   int x = Convert.ToInt32(d);  // returns 10
   string s = Convert.ToString(d);  //returns 10
   Boolean b = Convert.ToBoolean(d);  //return True
   Byte bt = Convert.ToByte(d); //return 10


Program to convert integer values from 0 to 255 into characters
  
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Typecasting1
{
    class ExConverting
    {
        static void Main(string[] args)
        {
            for (int i = 0; i <= 255; i++)
            {
                char c = Convert.ToChar(i);
                Console.Write(c);
                Console.Write(" ");
            }
            Console.ReadKey();
        }
    }
}

Output:

No comments:

Post a Comment