คำตอบสั้น: เหมือนกันทุกประการ (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 Type | Size | Range |
sbyte | System.SByte | 8-bit | -128 to 127 |
byte | System.Byte | 8-bit | 0 to 255 |
short | System.Int16 | 16-bit | -32,768 to 32,767 |
ushort | System.UInt16 | 16-bit | 0 to 65,535 |
int | System.Int32 | 32-bit | -2,147,483,648 to 2,147,483,647 |
uint | System.UInt32 | 32-bit | 0 to 4,294,967,295 |
long | System.Int64 | 64-bit | -9.22×10¹⁸ to 9.22×10¹⁸ |
ulong | System.UInt64 | 64-bit | 0 to 1.84×10¹⁹ |
float | System.Single | 32-bit | ±1.5×10⁻⁴⁵ to ±3.4×10³⁸ |
double | System.Double | 64-bit | ±5.0×10⁻³²⁴ to ±1.7×10³⁰⁸ |
decimal | System.Decimal | 128-bit | ±1.0×10⁻²⁸ to ±7.9×10²⁸ |
bool | System.Boolean | - | true/false |
char | System.Char | 16-bit | U+0000 to U+FFFF |
string | System.String | - | Reference Type |
object | System.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