String Template Class in C#

The StringTemplate class is part of the NString library that provides enhanced string formatting capabilities in C#. It offers a more readable alternative to String.Format by using named placeholders instead of numbered ones, making code less error-prone and easier to maintain.

The StringTemplate class comes with the NString library, which includes several useful extension methods for string manipulation such as IsNullOrEmpty(), IsNullOrWhiteSpace(), Join(), Truncate(), Left(), Right(), and Capitalize().

Syntax

The basic syntax for StringTemplate.Format uses named placeholders −

string result = StringTemplate.Format("{PropertyName}", new { PropertyName = value });

For formatting with specific format specifiers −

string result = StringTemplate.Format("{PropertyName:FormatSpecifier}", new { PropertyName = value });

StringTemplate vs String.Format

StringTemplate.Format String.Format
Uses named placeholders: {Name} Uses numbered placeholders: {0}
More readable and self-documenting Less readable with multiple parameters
Less prone to parameter order errors Easy to make parameter order mistakes
Requires anonymous objects or reflection Direct parameter passing

Using StringTemplate for Date Formatting

StringTemplate excels when formatting complex objects with multiple properties −

using System;

// Note: This example demonstrates the concept. 
// In practice, you would need to install the NString NuGet package
class Program {
    public static void Main() {
        var examInfo = new { 
            ExamName = "Mathematics Final", 
            ExamDate = new DateTime(2024, 6, 15),
            Duration = 180,
            Location = "Hall A"
        };
        
        // Simulating StringTemplate.Format behavior with String.Format
        string template = "The {0} exam will be held on {1:D} for {2} minutes in {3}";
        string result = String.Format(template, 
            examInfo.ExamName, 
            examInfo.ExamDate, 
            examInfo.Duration, 
            examInfo.Location);
            
        Console.WriteLine("Using String.Format:");
        Console.WriteLine(result);
        
        // This shows how StringTemplate would work (conceptually)
        Console.WriteLine("\nStringTemplate equivalent would be:");
        Console.WriteLine("StringTemplate.Format("{ExamName} will be held on {ExamDate:D} for {Duration} minutes in {Location}", examInfo)");
    }
}

The output of the above code is −

Using String.Format:
The Mathematics Final exam will be held on Saturday, June 15, 2024 for 180 minutes in Hall A

StringTemplate equivalent would be:
StringTemplate.Format("{ExamName} will be held on {ExamDate:D} for {Duration} minutes in {Location}", examInfo)

Benefits of Named Placeholders

StringTemplate's named placeholders provide several advantages over traditional string formatting −

using System;

class Program {
    public static void Main() {
        var student = new {
            FirstName = "John",
            LastName = "Smith", 
            Grade = 95.7,
            Subject = "Physics"
        };
        
        // Traditional String.Format - parameter order matters
        string traditional = String.Format(
            "Student: {1}, {0} scored {2:F1}% in {3}",
            student.FirstName, student.LastName, student.Grade, student.Subject);
        
        Console.WriteLine("Traditional approach:");
        Console.WriteLine(traditional);
        
        // StringTemplate approach would be more readable:
        Console.WriteLine("\nStringTemplate approach (conceptual):");
        Console.WriteLine("StringTemplate.Format("Student: {LastName}, {FirstName} scored {Grade:F1}% in {Subject}", student)");
        Console.WriteLine("Result: Student: Smith, John scored 95.7% in Physics");
    }
}

The output of the above code is −

Traditional approach:
Student: Smith, John scored 95.7% in Physics

StringTemplate approach (conceptual):
StringTemplate.Format("Student: {LastName}, {FirstName} scored {Grade:F1}% in {Subject}", student)
Result: Student: Smith, John scored 95.7% in Physics

Installation and Setup

To use StringTemplate in your C# project, you need to install the NString library via NuGet Package Manager −

Install-Package NString

Once installed, you can use the StringTemplate class and other NString extension methods in your application.

Conclusion

StringTemplate provides a more intuitive and maintainable approach to string formatting by using named placeholders instead of positional parameters. This reduces errors and makes code more readable, especially when dealing with complex formatting scenarios involving multiple properties.

Updated on: 2026-03-17T07:04:35+05:30

523 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements