0Pricing
C# Academy · Lesson

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

  1. Value Types vs Reference Types
  2. Boxing and Unboxing
  3. Implicit and Explicit Conversions
  4. The Convert Class and Parsing
← Back to C# Academy