Type Conversion in C#

The Type Conversions is very important for any language.There is a need to convert a data of one type to another type.It is used to store a value of one type to value of another type.
There are two type of conversion in C#.
  1. Implicit conversion
  2. Explicit conversion

     1. ) Implicit Conversions:
Implicit conversions are those that can always be performed without any loss of data.In implicit conversion we can convert only short range type values to long range type values.C# does this conversion automatically .But reverse is not true.Because short range type is the subset of long range type so that no data will be lost in implicit conversion.
short x= 10;
int y = x ;          is true
short z = y ;  is not true(reverse is not true)
There are an Implicit conversion hierarchy chart.

Description:- These arrows indicate the direction of implicit conversion from source to destination.
     2. ) Explicit Conversions:-
Explicit conversions are those that convert long range type values to short range type values.In this type of conversions data will be lost.Because here we convert long range type to short range type.This is known as casting.
       int to short
         uint to ushort
         long to int
         float to long
         double to long

type variable 1 = (type) variable 2 ;

Ex. 1:
int x = 25 ;
short y = (short) x ;
Ex. 2
float f = 15.0f ;
long l = (long ) f ;
Ex. 3
int x = 10 ;
string s = x. ToString();
Ex. 4
string s = "25";
int x = int.Parse(s);
int y = x + 5 ;
Output: 30
Ex. 5
int x = 25 ;
int y = 10 ;
short z = (short)x/(short)y ;
Difference between Int.Parse() and Convert.ToInt32():-
Int.parse():- This used only for convert the string values to the integer values.
String s = "50";
int x = s + 5 ;
output: 55
Convert.ToInt32():-This is used for convert the any type of values to the integer values.
Ex. 1
Object o = 25 ;
int x = Convert.ToInt32(O) + 10;
x  = 35
string s = "25";
int x = Convert.ToInt32(s) + 10;
x = 35 

For more:-
  1. Overview of C#
  2. Print the Grid Data in Windows Forms Application
  3. Compiling the C# codes
  4. Xml Application
  5. Ado.Net Application
  6. Make Custom Registration and Login page With Ajax in ASP.NET


Post a Comment

Powered by Blogger.