What's a good way of doing string templating in .NET?

Solution 1:

Here is the version for those of you who can use a new version of C#:

// add $ at start to mark string as template
var template = $"Your job finished at {FinishTime} and your file is available for download at {FileURL}."

In a line - this is now a fully supported language feature (string interpolation).

Solution 2:

Use a templating engine. StringTemplate is one of those, and there are many.

Example:

using Antlr.StringTemplate;
using Antlr.StringTemplate.Language;
 
StringTemplate hello = new StringTemplate("Hello, $name$", typeof(DefaultTemplateLexer));
hello.SetAttribute("name", "World");
Console.Out.WriteLine(hello.ToString());

Solution 3:

You can use the "string.Format" method:

var user = GetUser();
var finishTime = GetFinishTime();
var fileUrl = GetFileUrl();
var signature = GetSignature();
string msg =
@"Dear {0},

Your job finished at {1} and your file is available for download at {2}.

Regards,

--
{3}";
msg = string.Format(msg, user, finishTime, fileUrl, signature);

It allows you to change the content in the future and is friendly for localization.

Solution 4:

I wrote a pretty simple library, SmartFormat which meets all your requirements. It is focused on composing "natural language" text, and is great for generating data from lists, or applying conditional logic.

The syntax is extremely similar to String.Format, and is very simple and easy to learn and use. Here's an example of the syntax from the documentation:

Smart.Format("{Name}'s friends: {Friends:{Name}|, |, and}", user)
// Result: "Scott's friends: Michael, Jim, Pam, and Dwight"

The library has great error-handling options (ignore errors, output errors, throw errors). Obviously, this would work perfect for your example.

The library is open source and easily extensible, so you can also enhance it with additional features too.