Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

Cast Operator () ใน C# คืออะไร

Cast Operator ( )

ใช้สำหรับ Explicit Type Conversion (การแปลงชนิดข้อมูลแบบบังคับ) ระบุชนิดปลายทางในวงเล็บหน้าค่าที่ต้องการแปลง

Syntax

(TargetType)Expression

ตัวอย่างพื้นฐาน

using System;

namespace Demo {
    class Program {
        static void Main(string[] args) {
            double a = 4563.56;
            int x;
            
            // Cast double to int - ตัดทศนิยมทิ้ง
            x = (int)a;
            
            Console.WriteLine("Double: " + a);  // 4563.56
            Console.WriteLine("Int: " + x);     // 4563
            
            Console.ReadKey();
        }
    }
}

ประเภทการ Cast

1. Numeric Casting (Widening/Narrowing)

// Implicit (Widening) - ไม่ต้อง Cast
int i = 100;
long l = i;        // OK
double d = i;      // OK

// Explicit (Narrowing) - ต้อง Cast
double d = 3.14;
int i = (int)d;    // 3 - Truncate ทศนิยม

long big = 10000000000;
int small = (int)big; // Overflow Risk! ใช้ checked()

2. Reference Type Casting (Upcast/Downcast)

class Animal { }
class Dog : Animal { }
class Cat : Animal { }

Animal animal = new Dog(); // Upcast - Implicit (ปลอดภัย)
Dog dog = (Dog)animal;     // Downcast - Explicit (อาจ Fail รันไทม์)

// Safe Downcasting
if (animal is Dog d) {
    d.Bark(); // Pattern Matching (C# 7+)
}

// หรือ as Operator (คืน null ถ้าไม่ใช่)
Dog dog2 = animal as Dog;
if (dog2 != null) dog2.Bark();

3. Boxing/Unboxing

int val = 42;
object obj = val;        // Boxing - Implicit (Value Type -> Object)
int unboxed = (int)obj;  // Unboxing - Explicit (Object -> Value Type)

// ⚠️ Unboxing ต้อง Cast ไป Type เดียวกับที่ Box ไป
// object obj2 = 42;
// long l = (long)obj2; // ❌ InvalidCastException - ต้องเป็น (int) ก่อน

4. Custom Conversion Operators

public struct Temperature {
    public double Celsius { get; }
    
    public Temperature(double celsius) => Celsius = celsius;
    
    // Implicit: Temperature -> double
    public static implicit operator double(Temperature t) => t.Celsius;
    
    // Explicit: double -> Temperature
    public static explicit operator Temperature(double c) => new Temperature(c);
}

// ใช้งาน
Temperature t = new Temperature(25.5);
double c = t;              // Implicit - OK
Temperature t2 = (Temperature)30.0; // Explicit - ต้อง Cast

Cast vs Convert vs Parse

Method ใช้เมื่อ ตัวอย่าง Exception Risk
Cast ( ) Compatible Types, Reference Up/Downcast, Boxing/Unboxing (int)3.14, (Dog)animal InvalidCastException, OverflowException
Convert.ToXxx() General Conversion, String→Number, รองรับ null Convert.ToInt32("123") FormatException, OverflowException
Parse/TryParse String → Primitive (เฉพาะ String Input) int.Parse("123"), int.TryParse Parse: FormatException, TryParse: ไม่ Throw

Checked/Unchecked Context

// Checked - โยน OverflowException
int x = checked((int)3000000000L); // Throw OverflowException

// Unchecked - Wrap Around (Default สำหรับ Non-constant)
int y = unchecked((int)3000000000L); // -1294967296 (Wrap)

// Project Setting: Project Properties → Build → Advanced → Check for arithmetic overflow

Pattern Matching (C# 7+) - ทางเลือกที่ดีกว่า Cast

// แทนที่ (Dog)animal
if (animal is Dog dog) {
    dog.Bark(); // Type-safe, No Exception Risk
}

// Switch Expression (C# 8+)
string sound = animal switch {
    Dog d => "Woof",
    Cat c => "Meow",
    _ => "Unknown"
};

สรุป

  • Cast Operator (Type) ใช้สำหรับ Explicit Conversion
  • Numeric: Narrowing ต้อง Cast (อาจสูญเสียข้อมูล)
  • Reference: Downcast ต้อง Cast (อาจ Fail Runtime)
  • แนะนำ: ใช้ is Pattern Matching / as / TryParse แทน Cast ตรงๆ เพื่อความปลอดภัย