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

WBOY
Release: 2023-09-07 15:41:09
forward
890 people have browsed it

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;
Copy after login

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();
      }
   }
}
Copy after login

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 -

< h2>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();
      }
   }
}
Copy after login

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template