300x250 AD TOP

helooo
Tagged under:

C# type Conversions


Conversion is the process of changing the value of one Type to another. 
System.Convert class provides a complete set of methods for supported conversions.
In CSharp type conversions are divided into two , 
Implicit Conversions 
 Explicit Conversions .
Conversions declared as implicit occur automatically, when required and Conversions declared as explicit require a cast to be called.


                                   1:int ctr = 999;
                                    2:long count = ctr;
                    // implicit conversion from int type to long type

 





From the above statements , first line declare an integer type variable ctr and assigned 999 to it.
Second line declare a long type variable count and assign the value of ctr to count. Here the conversion occurred automatically.
Because we converted an integer type to long type . This type of conversion is called Implicit Conversion .

                             
                                    1:int ctr = 999;
                                   2:long count = ctr;
                 // implicit conversion from int type to long type
                                   3:int cnt = (int)count;
                // explicit conversion from long type to int type


 






We already saw the Implicit Conversion happened in the second line . The third line again we converted long Type to an integer type .
Here we explicitly convert long type to integer (int cnt = (int)count), otherwise the compiler will show
compiler errorError 1 Cannot implicitly convert type 'long' to 'int'. An explicit conversion exists (are you missing a cast?) .
This type of conversion is called Explicit Conversion .