Implicit and Explicit Conversions
Convert between compatible types safely.
Converting Between Types
C# can convert one numeric type to another. Some conversions happen automatically (implicit), while others need an explicit cast.
using System;
class Program
{
static void Main()
{
int i = 10;
double d = i; // implicit
int back = (int)d; // explicit
Console.WriteLine(d + ", " + back);
}
}Implicit (Widening) Conversions
An implicit conversion is allowed when no data can be lost, such as int to long or int to double. No cast is needed.
using System;
class Program
{
static void Main()
{
int i = 42;
long l = i; // widening, safe
double d = i; // widening, safe
Console.WriteLine(l + ", " + d);
}
}All lessons in this course
- Value Types vs Reference Types
- Boxing and Unboxing
- Implicit and Explicit Conversions
- The Convert Class and Parsing