I may be necessary to convert one type to another. There are two types of type conversion implicit and explicit.
- Implicit: Automatic compiler conversion where data loss is not an issue.
- Explicit: A conversin where data loss may happen and is recommended that the programmer writes additional processing
A common rule of thumb is that it is much easier to convert up then it is to convert down. For example, conversion from int to long is an easy operation, but converting the other way around is not so easy. Remember the long data type is a bigger type then the int data type is. To prevent data loss just remember to convert from small to large.
There may be situations where you cannot get around from converting a large data type to small. This where explicit conversion comes into play.
[edit] Csharp Implicit Conversion
using System;
class Program
{
static void Main(string[] args)
{
int x = 2;
double y = 12.2;
double z;
z = x + y; //x is automatically converted into a double
Console.WriteLine(z);
Console.Read();
}
}
Output
14.2
This is an example of csharp implicit conversion. The compiler implicitly converts x to a double. Data loss is not an issue with this operation.
[edit] Csharp Explicit Conversion
using System; class Program { static void Main(string[] args) { double x = 2.1; int y = 12; int z = (int)x + y; //Explicit conversion from double to int Console.WriteLine(z); Console.Read(); } }
- Line 10: (data type to convert to)variable which is (int)x
x was initialized to 2.1 but was converted to an int so for Line 10 x equaled 2.
|