Can you please explain the difference between explicit
and implicit
type casts?
Explicit cast:
int x = 0;
float y = 3.8f;
x += (int) y; //Explicit cast.
This tells the compiler that the cast was intentional and that you know that the fractional part will go lost. The compiler won't complain.
Implicit cast:
int x = 0;
float y = 3.8f;
x += y; //Implicit cast
The compiler will complain because the fractional part will be lost when converting float to int.
Explicit Conversions
If a conversion cannot be made without a risk of losing information then it is an explicit conversion.
For example -
class ExplicitConversions
{
static void Main()
{
int x;
double y = 6358.057;
// Cast double to int.
x = (int)y;
System.Console.WriteLine(x);
}
}
Implicit Conversions
If a conversion can be made without a risk of losing information then it is an implicit conversion. No special syntax is required because the conversion is type safe and no data is lost.
For example -
class ImplicitConversions
{
static void Main()
{
int x = 6714;
double y;
// Cast int to double.
y = x;
System.Console.WriteLine(y);
}
}
A simple search will give lots of informations in the net.
difference between implicit and explicit type
int i = 2;
float a = i; // Implicit
float b = (float)i; // Explicit