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

ความแตกต่างระหว่าง int และ Int32 ใน C#

คำตอบสั้น: เหมือนกันทุกประการ (Alias)

  • int = C# Keyword (Alias)
  • Int32 = .NET Framework Type (System.Int32)
  • Compile เป็น IL Code เดียวกันหมด
  • Runtime ไม่มีความแตกต่างใดๆ

การประกาศ


// ทั้งคู่เท่ากัน
Int32 x = 5;   // ใช้ต้อง using System; หรือ System.Int32
int y = 5;     // C# Keyword

// Type Check
typeof(int) == typeof(Int32) == typeof(System.Int32) // true

ตัวอย่างโค้ด


using System;

namespace DemoApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            Int32 x = 5;
            int y = 5;
            
            Console.WriteLine($"Int32: {x}"); // 5
            Console.WriteLine($"int: {y}");   // 5
            Console.WriteLine($"Same type: {typeof(int) == typeof(Int32)}"); // True
            
            Console.ReadLine();
        }
    }
}

Output

Int32: 5
int: 5
Same type: True

Alias ทั้งหมดใน C# (Built-in Types)

C# Keyword.NET TypeSizeRange
sbyteSystem.SByte8-bit-128 to 127
byteSystem.Byte8-bit0 to 255
shortSystem.Int1616-bit-32,768 to 32,767
ushortSystem.UInt1616-bit0 to 65,535
intSystem.Int3232-bit-2,147,483,648 to 2,147,483,647
uintSystem.UInt3232-bit0 to 4,294,967,295
longSystem.Int6464-bit-9.22×10¹⁸ to 9.22×10¹⁸
ulongSystem.UInt6464-bit0 to 1.84×10¹⁹
floatSystem.Single32-bit±1.5×10⁻⁴⁵ to ±3.4×10³⁸
doubleSystem.Double64-bit±5.0×10⁻³²⁴ to ±1.7×10³⁰⁸
decimalSystem.Decimal128-bit±1.0×10⁻²⁸ to ±7.9×10²⁸
boolSystem.Boolean-true/false
charSystem.Char16-bitU+0000 to U+FFFF
stringSystem.String-Reference Type
objectSystem.Object-Base Type

แนวทางปฏิบัติ (C# Coding Conventions)

  • ✅ ใช้ C# Keyword (int, string, bool...) ในโค้ด Application - อ่านง่าย เป็น Idiomatic C#
  • ✅ ใช้ .NET Type (Int32, String, Boolean...) เมื่อ:
    • เขียน Library/Framework Code
    • Interop กับภาษาอื่น (VB.NET, F#)
    • Reflection / Serialization / Generic Type Parameters
    • Documentation/API Spec
  • ✅ Consistency: เลือกหนึ่งแบบใน Project/Team ให้เหมือนกัน

ข้อแตกต่างเล็กน้อย (Edge Cases)


// 1. Generic Type Parameter - ต้องใช้ .NET Type
List<Int32> list1;    // OK
List<int> list2;      // OK (C# allows both)

// 2. typeof() - ใช้ได้ทั้งคู่
typeof(int)           // OK
typeof(Int32)         // OK
typeof(System.Int32)  // OK

// 3. Default Value
default(int)          // 0
default(Int32)        // 0

// 4. Constant Declaration
const int MaxInt = int.MaxValue;     // OK
const Int32 MaxInt2 = Int32.MaxValue; // OK