Saturday, 7 May 2011

Data Types in C#

C# DataTypes

    Data Types means what type of data a variable can hold . C# is a strongly typed language, therefore every variable and object must have a declared type. The C# type system contains three Type categories.
      Value Types
      Reference Types
      Pointer Types
  In C# it is possible to convert a value of one type into a value of another type . The operation of Converting a Value Type to a Reference Type is called Boxing and the reverse operation is called Unboxing .
Ex.    int month;
                 int : is the data type
                 month: is the variable name
int
int can store signed 32 bit integer values in the range of -2,147,483,648 to +2,147,483,647
C# Runtime type : System.Int32
C# declaration : int month;
C# Initialization : month = 10;
C# default initialization value : 0
decimal
Decimal is of a 128-bit data type.The approximate range and precision for the decimal type are -1.0 X 10-28 to 7.9 X 1028
C# Runtime type : System.Decimal
C# declaration : decimal val;
C# Initialization : val = 0.12;
C# default initialization value : 0.0M
string
Represents a string of Unicode characters. string variables are stored any number of alphabetic,numerical, and special characters .
C# Runtime type : System.String
C# declaration : string str;
C# Initialization : str = ".Net Environment";
bool
Bool is used to declare variables to store the Boolean values, true and false. In C# , there is no conversion between the bool type and other types.
C# Runtime type : System.Boolean
C# declaration : bool flag;
C# Initialization : flag = true;
C# default initialization value : false
         The following list shows the list of data types available in C# and their corresponding class/struct in .NET class library.
C# Data type Mapped to .NET class/struct
sbyte System.SByte
byte System.Byte
char System.Char
float System.Single
decimal System.Decimal
double System.Double
ushort System.UInt16
short System.Int16
uint System.UInt32
int System.Int32
ulong System.UInt64
long System.Int64
bool System.Boolean
string System.String
object System.Object

Boxing:
Converting value types to reference types is also known as boxing. As can be seen in the example below, it is not necessary to tell the
compiler an Int32 is boxed to an object, because it takes care of this itself.
e.g.-   Int32 a = 10;
            object count = a ; // Implicit boxing
            Console.WriteLine("The Object count = {0}",count); // prints out 10
              //However, an Int32 can always be explicitly boxed like this:
             Int32 a = 10;
             object count = (object) a; // Explicit boxing
             Console.WriteLine("The object count = {0}",count); // prints out 10

Unboxing: The following example intends to show how to unbox a reference type back to a value type. First an Int32 is boxed to an object, and then it is
unboxed again. Note that unboxing requires explicit cast.
Ex.      Int32 a = 5;
                   object count = a; // Implicit
                   Boxing a = (int)count; // Explicit Unboxing
 

Type Conversions  Conversion is based on type compatibility and data compatibility.
1. Implicit Conversion

2. Explicit Conversion

Implicit Conversion   In implicit conversion the compiler will make conversion for us without asking.

char -> int -> float is an example of data compatibility.
 


using System;
class Program
    {
        static void Main(string[] args)
        {
            int x =10000;
            int y =20000;
            long total;
            // In this the int values are implicitly converted to long data type;
            //you need not to tell compiler to do the conversion, it automatically does.
            total = x + y;
            Console.WriteLine("Total is : " + total);
            Console.ReadLine();
        }
    }
Explicit Conversion
    In explicit conversion we specifically ask the compiler to convert the value into another data type.  CLR checks for data compatibility at runtime.
 


using System;
class Program
   {
      static void Main(string[] args)
       {
          int x = 65; 
          char value;
          value = (char)x;
            // In this the int values are explicitly converted to char data type;
            //you have to tell compiler to do the conversion, it uses casting.
            Console.WriteLine("Value is: " + value);
            Console.ReadLine();
        }
    }

Microsoft .NET provides three ways of type conversion:

1. Parsing
2. Convert Class
3. Explicit Cast Operator ()
 

Parsing
Parsing is used to convert string type data to primitive value type. For this we use parse methods with value types.
 


using System;
class Program
  {
   static void Main(string[] args)
    {
           //using parsing
            int number;
            float weight;
            Console.Write("Enter any number : ");
            number = int.Parse(Console.ReadLine());
            Console.Write("Enter your weight : ");
            weight = float.Parse(Console.ReadLine());
            Console.WriteLine("You have entered : " + number);
            Console.WriteLine("You weight is : " + weight);
            Console.ReadLine();
    }
   }
Convert Class
Convert class contains different static methods like ToInt32(), ToInt16(), ToString(), ToDateTime() etc used in type conversion.
 


using System;
   class Program
    {
        static void Main(string[] args)
        {
            // example of using convert class
             string num = "23";
            int number = Convert.ToInt32(num);
            int age = 24;
            string vote = Convert.ToString(age);
            Console.WriteLine("Your number is : " + number);
            Console.WriteLine("Your voting age is : " + age);
            Console.ReadLine();
        }
    }

Explicit Cast Operator ()
It can used with any type having type compatibility and data type compatibility.
 


using System;
    class Program
    {
        static void Main(string[] args)
        {
            int num1, num2;
            float avg;
            num1 = 10;
            num2 = 21;
            avg = (float)(num1 + num2) / 2;
            Console.WriteLine("average is : " + avg);
            Console.ReadLine();
        }
    }

No comments:

Post a Comment