Sep 1, 2015

Type Conversions

C# supports two kinds of type conversions: implicit conversions and explicit conversions. Some of the predefined types define predefined conversions, such as converting from an int type to a long type.
Implicit conversions are conversions in which one type can directly and safely are converted to another type. Generally, small range type converts to large range type. As an example, you’ll examine the process of converting from an int type to a long type. In this conversion, there is no loss of data, as shown in Listing 18.
 Conversion example

 
using System;
class ConversionSamp
{
static void Main()
©2013 Mahesh Chand
27
{
int num1 = 123;
long num2 = num1;
Console.WriteLine(num1.ToString());
Console.WriteLine(num2.ToString());
}
}


Casting performs explicit conversions. There may be a chance of data loss or even some errors in explicit conversions. For example, converting a long value to an integer would result in data loss.


This is an example of an explicit conversion:
long num1 = Int64.MaxValue;
int num2 =(int)num1;
Console.WriteLine(num1.ToString());
Console.WriteLine(num2.ToString());
The process of converting from a value type to a reference type is called boxing. Boxing is an implicit conversion. Listing 19 shows an example of boxing.


 Boxing example
using System;
class ConversionSamp
{
static void Main()
{
int num1 = 123;
Object obj = num1;
Console.WriteLine(num1.ToString());
Console.WriteLine(obj.ToString());
}
}


The process of converting from a reference type to a value type is called unboxing.example of unboxing.

 
. Unboxing example
using System;
class ConversionSamp
{
static void Main()
{
Object obj = 123;
int num1 = (int)obj;
Console.WriteLine(num1.ToString());
Console.WriteLine(obj.ToString());
}
}

No comments:

Post a Comment