Type Conversions ใน C# มี 2 แบบ: Implicit และ Explicit
Implicit Type Conversion
Compiler ทำให้อัตโนมัติอย่าง Type-safe เช่น แปลงจาก Type เล็กไปใหญ่ (int -> long) หรือ Derived Class -> Base Class
ตัวอย่าง: int -> long
int val1 = 11000; int val2 = 35600; long sum; sum = val1 + val2; // Implicit conversion
Compiler แปลง int เป็น long เอง ไม่ Error
ตัวอย่างโค้ด
using System;
using System.IO;
namespace Demo
{
class Program
{
static void Main(string[] args)
{
int val1 = 11000;
int val2 = 35600;
long sum = val1 + val2;
Console.WriteLine("Sum = " + sum); // 46600
Console.ReadLine();
}
}
}