What is the difference between implicit and explicit type conversion in C#?



The following is the difference between implicit and explicit type conversion −

Implicit Type Conversion

These conversions are performed by C# in a type-safe manner.

To understand the concept, let us implicitly convert int to long.

int val1 = 11000; int val2 = 35600; long sum; sum = val1 + val2;

Above, we have two integer variable and when we sum it in a long variable, it won’t show an error. Since the compiler does the implicit conversion on its own.

Let us print the values now.

Example

using System; using System.IO; namespace Demo {    class Program {       static void Main(string[] args) {          int val1 =34567;          int val2 =56743;          long sum;          sum = val1 + val2;          Console.WriteLine("Sum= " + sum);          Console.ReadLine();       }    } }

Explicit Type Conversion

These conversions are done explicitly by users using the pre-defined functions.

Let us see an example to typecast double to int −

Example

using System; namespace Program {    class Demo {       static void Main(string[] args) {          double d = 1234.89;          int i;          // cast double to int.          i = (int)d;          Console.WriteLine(i);          Console.ReadKey();       }    } }
Updated on: 2020-06-21T15:03:14+05:30

948 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements