Pages

Thursday, May 9, 2013

How to convert one datatype to another datatype?


Type conversion is a process of converting one type into another. Using C# type conversion techniques, not only you can convert data types, you can also convert object types. The type conversion in C# can be either implicit conversion or an explicit conversion. If one type of data is automatically converted into another type of data, it is known as implicit conversions. There is no data loss due to implicit conversion. But explicit conversion is a forced conversion and there may be a data loss. Type conversions occur mainly when we pass arguments to a function or mixing mode arithmetic etc. 

1.compatible data type
ex:
    int x=20;
   long y1=x;  // implicit conversion
 short s1=x; // wrong metho bec int is 4 byte & short is 2 byte( in this case u must follow explicity data conversion)

 ex:
  int x=20;
short s1=(short)x;  // explicit conversion

ex:
long x;int y = 25;
x = y; //implicit numerical conversion





Note: Implicit & explicity only around between compatable data type only

2.For performing conversion between incompatible data type we need to use the method present in the convert class
ex:
 string s="1235";
int i=s; // wrong method(not possable)
int i=convert.toint32(s); //wright method
Note:
suppose if  u want to convert int to string then used
  convert.tostring(); method

No comments:

Post a Comment