avatarChanghui Xu

Summary

This article discusses two methods for formatting strings using templates in C#: string.Format() and Template Modeling.

Abstract

The article begins by introducing C#'s String Interpolation feature for formatting strings in a flexible and readable way. However, it notes that this method may not work in scenarios where predefined templates are required, such as log messages, alerts, or email templates. To address this, the article presents two simple methods for substituting parameters with values in a string template without using third-party libraries.

The first method is the string.Format() method, which takes a template with indexed placeholders and a list of objects to replace these placeholders. This method is straightforward but may not be the most readable when dealing with many parameters.

The second method is Template Modeling, which involves creating a class to model the construction and rendering of a predefined string template. This method uses named parameters wrapped with escape characters, improving readability when dealing with many parameters. The class constructor can also serve as a validator and value transformer for parameters.

The article concludes by cautioning against using these methods to generate SQL queries or statements and recommends sanitizing objects to avoid template disruption. The full solution can be found in the author's GitHub repository.

Bullet points

  • C# has a feature called String Interpolation for formatting strings.
  • String Interpolation may not work for predefined templates like log messages, alerts, or email templates.
  • The string.Format() method is a common way to format strings using indexed placeholders and a list of objects.
  • Template Modeling is a method that uses named parameters for improved readability with many parameters.
  • Template Modeling involves creating a class to model the construction and rendering of a predefined string template.
  • The class constructor can serve as a validator and value transformer for parameters.
  • It is recommended to sanitize objects to avoid template disruption.
  • These methods should not be used to generate SQL queries or statements.
  • The full solution can be found in the author's GitHub repository.

Formatting Strings using Templates in C#

How to Render String Templates in C#

C# has a feature, String Interpolation, to format strings in a flexible and readable way. The following example demonstrates the way how we usually output a string when we have data beforehand then pass data to the template string.

On the other hand, the String Interpolation doesn’t work in some scenarios when we want to format certain strings following predefined templates. The string can be, for example, a log message, an alert, an Email template, and so on.

To solve this problem, we can use some NuGet packages (e.g., Nustache, Stubble, mustache#) to render templates by substituting parameters that are wrapped in specific syntaxes with desired values. These libraries work like view engines that are able to compile templates with complex logic.

In this article, instead of using those libraries, I will show you two simple ways to substitute parameters with values in a string template. The full solution can be found in my GitHub repository.

string.Format()

The most common way to format strings is using the string.Format() method. This method takes a template which contains indexes as placeholders and takes a list of objects for stubbing out indexed parameters. Let's take a look at the following example.

In the code above, line 1 defines the string template, which is a constant and contains two indexes: 0 and 1. Besides the indexes, we can also add the formatter to each object. Line 2 generates a string based on two objects, and line 3 writes the string to the Console. Similarly, line 4 writes a string directly to Console.

Using the string.Format() method, we can easily replace the placeholders with desired values. The only problem is that indexes do not convey much meaning when we read the code. Therefore, this way works the best when the number of parameters is small.

Template Modeling

In case when a string template contains many parameters, we probably want to use named parameters instead of indexes to improve the readability. Then we need to utilize some kind of template syntax like mustache or handlebar. Rather than installing a third-party library, we can quickly implement something on our own. I name this way as “template modeling” because we are going to model the target string as a class.

Let’s take a look at the following example.

In the code snippet above, we define a class MyString to model the construction and rendering of a predefined string template. In the MyString class, a private dictionary _parameters is used to store the string placeholders and their values. The named placeholders can be wrapped with some escape characters that are distinct from the other content in the template.

The constructor, lines 9 to 16, can be served as a validator for parameters so that they are ensured to be correct or have some fallback values, and can be served as value transformer so that each template segment can be replaced with a transformed value based on business logic.

Lastly, the public ToString() method simply returns the formatted the string based on the static template and input parameters. Inside the ToString() method, line 20 uses a LINQ expression which gracefully replaces all template segments with stored values.

This way allows us to easily write unit tests with different parameters.

A word of caution is that you may want to sanitize the objects so that they won’t mess up with your template. For example, it is a good idea to sanitize the inputs for an HTML email template to avoid injection. Also, don’t use any of these methods to generate SQL queries or statements. Entity Framework has already have a method for generating raw SQL.

That’s all for today. Again the code is in my GitHub repository. Thanks for reading.

Csharp
Programming
Dotnet
Technology
Coding
Recommended from ReadMedium