Home  >  Article  >  Backend Development  >  What is the difference between implicit type conversion and explicit type conversion in C#?

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

WBOY
WBOYforward
2023-09-07 15:41:09891browse

C# 中隐式类型转换和显式类型转换有什么区别?

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

Implicit type conversion

C# in a type-safe manner Perform these transformations.

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

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

sum = val1 + val2;

Above, we have two integer variables and when we accumulate them into a long integer variable, no error will be displayed. Because the compiler will perform implicit conversions by itself.

Now let’s print these values.

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 the user using predefined functions.

Let's see an example of converting double type 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();
      }
   }
}

The above is the detailed content of What is the difference between implicit type conversion and explicit type conversion in C#?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete