Giới thiệu
Toán tử nameof (C# 6+) trả về tên string literal của biến, kiểu, thành viên, namespace, ... tại **compile-time**. Không tốn chi phí runtime, an toàn refactor (rename -> tự cập nhật).
Ví dụ cơ bản
var vehicle = "motorbike"; Console.WriteLine(nameof(vehicle)); // "vehicle"
Ví dụ hoàn chỉnh
using System;
public class Program
{
static void Main()
{
var vehicle = "motorbike";
Console.WriteLine(nameof(vehicle)); // vehicle
var time = DateTime.Now.ToLocalTime();
Console.WriteLine(nameof(time)); // time
var a = false;
Console.WriteLine(nameof(a)); // a
}
}
Kết quả
vehicle time a
Các trường hợp dùng nameof
| Đối tượng | Ví dụ | Kết quả |
|---|---|---|
| Biến cục bộ | nameof(x) | "x" |
| Tham số phương thức | nameof(param) | "param" |
| Thuộc tính/Field | nameof(obj.Prop) | "Prop" |
| Kiểu/Class | nameof(List<int>) | "List" |
| Namespace | nameof(System.Collections) | "Collections" |
| Enum member | nameof(Color.Red) | "Red" |
Ứng dụng thực tế quan trọng
1. INotifyPropertyChanged / MVVM
public string Name
{
get => _name;
set { _name = value; OnPropertyChanged(nameof(Name)); }
}
2. ArgumentNullException
public void Foo(string bar)
{
if (bar == null) throw new ArgumentNullException(nameof(bar));
}
3. Logging/Diagnostics
logger.LogInfo($"Method {nameof(ProcessOrder)} started");
Lưu ý
- Chỉ chấp nhận biểu thức đơn giản (simple name, member access). Không dùng với biểu thức phức tạp:
nameof(x + y)lỗi compile. - Không đánh giá biểu thức - không có side effect.
- Thay thế cho "magic strings" cứng nhắc.