Câu trả lời ngắn gọn
Không có khác biệt gì về mặt runtime.
int là alias (bí danh) của System.Int32. Chúng compile thành IL giống hệt nhau.
Chi tiết
| Đặc điểm | int | Int32 / System.Int32 |
|---|---|---|
| Bản chất | C# Keyword (alias) | .NET Framework Type (struct) |
| Namespace | Không cần (global) | System (hoặc using System) |
| Kích thước | 32-bit signed integer | 32-bit signed integer |
| Range | -2,147,483,648 đến 2,147,483,647 | -2,147,483,648 đến 2,147,483,647 |
| IL Type | int32 | int32 |
| Default value | 0 | 0 |
Ví dụ minh họa
using System;
class Program
{
static void Main()
{
// Cả hai đều OK
int a = 5;
Int32 b = 5; // Cần using System; hoặc System.Int32
System.Int32 c = 5; // Fully qualified
Console.WriteLine(a == b); // True
Console.WriteLine(a.GetType() == b.GetType()); // True
Console.WriteLine(typeof(int) == typeof(Int32)); // True
Console.WriteLine(typeof(int) == typeof(System.Int32)); // True
// Max/Min values
Console.WriteLine(int.MaxValue); // 2147483647
Console.WriteLine(Int32.MaxValue); // 2147483647
Console.WriteLine(int.MinValue); // -2147483648
}
}
Tất cả C# Aliases vs .NET Types
| C# Keyword | .NET Type | Kích thước | Signed? |
|---|---|---|---|
sbyte | System.SByte | 8-bit | Yes |
byte | System.Byte | 8-bit | No |
short | System.Int16 | 16-bit | Yes |
ushort | System.UInt16 | 16-bit | No |
int | System.Int32 | 32-bit | Yes |
uint | System.UInt32 | 32-bit | No |
long | System.Int64 | 64-bit | Yes |
ulong | System.UInt64 | 64-bit | No |
float | System.Single | 32-bit | IEEE 754 |
double | System.Double | 64-bit | IEEE 754 |
decimal | System.Decimal | 128-bit | Yes |
bool | System.Boolean | 1-bit (logical) | N/A |
char | System.Char | 16-bit | Unicode |
string | System.String | Variable | Reference |
object | System.Object | Reference | Base type |
Khi nào dùng int vs Int32?
Ưu tiên int (C# keyword)
- Code C# thông thường - idiomatic, readable.
- Không cần
using System;. - Team convention thường dùng keyword.
Dùng Int32 / System.Int32 khi
- Code generation, reflection, serialization libraries.
- Interop với ngôn ngữ khác (VB.NET, F#) - họ dùng
Int32. - API công khai cross-language (CLS-compliant).
- Documentation, spec viết về .NET types.
- Generic constraints:
where T : Int32(không dùngint).
Lưu ý thú vị
// C# cho phép dùng keyword trong typeof
typeof(int) == typeof(Int32) == typeof(System.Int32) // All true
// Nhưng trong một số context cần type name string
Type.GetType("System.Int32") // OK
Type.GetType("int") // null - không hiểu keyword
// Serialization/Config thường dùng fully qualified name
// JSON: {"$type": "System.Int32", "$value": 42}
Performance
Zero difference. C# compiler dịch int thành System.Int32 trong metadata. JIT compiler thấy cùng một kiểu.
Best Practice
Quy ước chung: Dùng C# keywords (
int, string, bool, object...) trong code logic. Dùng CLR type names (Int32, String, Boolean...) khi làm việc với reflection, serialization, interop, hoặc documentation kỹ thuật.