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

Numeric Promotion ใน C# (Arithmetic Operators)

Numeric Promotion ใน Arithmetic Operators: Operand เล็กถูก Promote ให้เป็น Type ใหญ่ก่อนทำ Operation

ตัวอย่าง: short * ushort → int

using System;

class Program {
    static void Main() {
        short val1 = 99;      // 16-bit Signed
        ushort val2 = 11;     // 16-bit Unsigned
        
        // Both Promoted to int Before Multiplication
        int result = val1 * val2; // 1089
        
        Console.WriteLine($"Result: {result}, Type: {result.GetType()}");
        // Result: 1089, Type: System.Int32
    }
}

Promotion Rules (Arithmetic)

  1. decimal present → All to decimal
  2. double present → All to double
  3. float present → All to float
  4. ulong present → All to ulong
  5. long present → All to long
  6. uint present → All to uint (or long if mixed Signed)
  7. Otherwise → All to int (short, byte, sbyte, char, ushort → int)

ตัวอย่าง Promotion Scenarios

byte a = 10, b = 20;
var r1 = a + b;        // int (Not byte! Overflow Risk if byte)
var r2 = a * b;        // int
var r3 = a / b;        // int

short s = 100;
int i = 200;
var r4 = s + i;        // int
var r5 = s * i;        // int

uint u = 100;
long l = 200;
var r6 = u + l;        // long (uint + long → long)

float f = 1.5f;
double d = 2.5;
var r7 = f + d;        // double

decimal m = 1.5m;
double d2 = 2.5;
var r8 = m + d2;       // decimal (decimal + double → decimal? No! Compile Error)
// decimal + double → NO Implicit Conversion! Must Cast.
var r8fixed = m + (decimal)d2; // decimal

⚠️ Common Pitfalls

1. Byte/Short Arithmetic → int Result

byte x = 200, y = 100;
byte z = (byte)(x + y); // Need Cast! x+y = 300 (int) → Truncates to 44
// ถ้าไม่ Cast: Compile Error "Cannot implicitly convert int to byte"

2. No Implicit Conversion Between Signed/Unsigned Same Size

int i = 10;
uint u = 20;
// var r = i + u; // ❌ Error: No Implicit Conversion Between int and uint
var r = (long)i + u; // ✅ Explicit Cast to Common Larger Type

3. Decimal + Float/Double = Compile Error

decimal d = 1.0m;
double db = 2.0;
// var r = d + db; // ❌ Error
var r = d + (decimal)db; // ✅

Best Practices

  • ใช้ int / long / double / decimal เป็นหลัก — หลีกเลี่ยง Promotion Issues
  • ระวัง byte/short Arithmetic — ผลลัพธ์เป็น int ต้อง Cast กลับ
  • ใช้ checked Block สำหรับ Overflow Detection
  • Explicit Cast เมื่อผสม Signed/Unsigned หรือ Decimal/Float