StringTemplate thuộc thư viện NString (NuGet: NString), cung cấp formatting với named placeholder thay vì positional {0}.
Cài đặt
dotnet add package NString
Ví dụ sử dụng
using NString;
class Program
{
static void Main()
{
var person = new { Name = "An", Age = 25, City = "Hà Nội" };
// StringTemplate.Format - named placeholders
string result = StringTemplate.Format(
"{Name} is {Age} years old, lives in {City}",
person);
Console.WriteLine(result);
// Output: An is 25 years old, lives in Hà Nội
// So với String.Format (positional)
string oldWay = string.Format("{0} is {1} years old, lives in {2}",
person.Name, person.Age, person.City);
// Format datetime
var exam = new { ExamName = "Midterm", ExamDate = DateTime.Now };
string formatted = StringTemplate.Format(
"{ExamName} will held on {ExamDate:yyyy-MM-dd}",
exam);
Console.WriteLine(formatted);
}
}
So sánh
| Đặc điểm | String.Format | StringTemplate.Format |
|---|---|---|
| Placeholder | Số thứ tự {0}, {1} | Tên property {Name}, {Age} |
| Đọc hiểu | Khó với nhiều tham số | Dễ đọc, tự tài liệu hóa |
| Thứ tự | Phụ thuộc vị trí | Không phụ thuộc thứ tự |
| Type safety | Runtime | Runtime (reflection) |
| Performance | Nhanh hơn | Chậm hơn (reflection) |
C# 6+ String Interpolation (built-in, khuyên dùng)
var person = new { Name = "An", Age = 25 };
string modern = $"{person.Name} is {person.Age} years old";
// Nhanh, type-safe, readable - không cần thư viện ngoài
Lưu ý: StringTemplate dùng reflection → chậm hơn. Ưu tiên $"" interpolation (C# 6+) cho hầu hết trường hợp.