Wednesday, 29 January 2014

DATA TYPES CONVERSION IN C#



Type conversion is basically type casting or converting one type of data to another type. In C#, type casting has two forms:
  • Implicit type conversion - these conversions are performed by C# in a type-safe manner. Examples are conversions from smaller to larger integral types and conversions from derived classes to base classes.
  • Explicit type conversion - these conversions are done explicitly by users using the pre-defined functions. Explicit conversions require a cast operator.


Implicit conversion
For Example


using System;

namespace Project
{
  class Implicit
 {
    static void Main(String[] args)
   {
     double b=25.301;
    int i=(int)b;
    Console.WriteLine("Conversion to int :{o}",i);
    Console.ReadLine();
   }

 }

}

OUTPUT:
25


Following Methods for Explicit Function



S.NMethods & Description
1ToBoolean
Converts a type to a Boolean value, where possible.
2ToByte
Converts a type to a byte.
3ToChar
Converts a type to a single Unicode character, where possible.
4ToDateTime
Converts a type (integer or string type) to date-time structures.
5ToDecimal
Converts a floating point or integer type to a decimal type.
6ToDouble
Converts a type to a double type.
7ToInt16
Converts a type to a 16-bit integer.
8ToInt32
Converts a type to a 32-bit integer.
9ToInt64
Converts a type to a 64-bit integer.
10ToSbyte
Converts a type to a signed byte type.
11ToSingle
Converts a type to a small floating point number.
12ToString
Converts a type to a string.
13ToType
Converts a type to a specified type.
14ToUInt16
Converts a type to an unsigned int type.
15ToUInt32
Converts a type to an unsigned long type.
16ToUInt64
Converts a type to an unsigned big integer.

For Example

using System;

namespace TypeC
{
  class Type
{
   static void Main(String[] args)
   {
    double b=123.045;
    int p=234;
    float q=25.09f;
   bool w=true;
   
   Console.WriteLine(b.ToString());
   Console.WriteLine(p.ToString());
 Console.WriteLine(q.ToString());
 Console.WriteLine(w.ToString());
  
    }
}
}

OUTPUT:
123.045
234
25.09
true



No comments:

Post a Comment