Custom String Interpolation

In .NET 6, custom string interpolation is a powerful and flexible feature that allows you to define your own string interpolation behavior. With custom string interpolation, you can format strings in a way that makes sense for your specific use case. In this article, we’ll take a look at how you can use the InterpolatedStringHandler attribute in .NET Core to create your own custom string interpolation.

Basic String Interpolation

At its core, string interpolation is a way to embed expressions inside string literals. For example, in C#, you might use string interpolation to format a string like this:

string name = "Kevin";
int age = 39;

string message = $"Hello, my name is {name} and I'm {age} years old.";

This creates a string message that contains the values of name and age inserted into the string literal.

While the built-in string interpolation in C# is certainly useful, it’s also limited. What if you want to format strings in a way that doesn’t make sense for the built-in string interpolation? What if you want to format strings in a way that’s specific to your application or domain?

Custom Interpolation

This is where custom string interpolation comes in. With custom string interpolation, you can create your own string interpolation behavior. Here’s an example of how you might use custom string interpolation in C#:


using System.Runtime.CompilerServices;
using System.Text;

SimpleConsoleLogger.Log($"Interpolated {1} 2nd part {2} 3rd part {DateTime.Now}");

[InterpolatedStringHandler]
public ref struct MessageInterpolatedStringHandler
{
    private readonly StringBuilder _messageStringBuilder;
    private int _count = 0;

    public MessageInterpolatedStringHandler(int literalLength, int formattedCount)
    {
        _messageStringBuilder = new StringBuilder(literalLength);
    }

    public void AppendLiteral(string s)
    {
        _messageStringBuilder.Append(s);
    }

    public void AppendFormatted<T>(T t)
    {
        _count++;
        _messageStringBuilder.Append(t);
    }

    public string BuildMessage() =>
        _messageStringBuilder.ToString();
}

public static class SimpleConsoleLogger
{
    public static void Log(string message)
    {
        Console.WriteLine(message);
    }

    public static void Log(MessageInterpolatedStringHandler handler)
    {
        Console.WriteLine(handler.BuildMessage());
    }
}

In this example, if you were to call the SimpleConsoleLogger’s Log method with with a non interpolated string the first function would be called, but if you passed an interplated string the second method would be called. The custom string handler can altered to provide custom behavor when a literal or formated type is used in the string.

Video

Here is a video I made indroducing the concept with examples:

Conclusion

Custom string interpolation in .NET 6 is a must-have feature for anyone looking to format strings in a way that’s specific to their application or domain. With the InterpolatedStringHandler attribute and the IFormatProvider and ICustomFormatter interfaces, you can create your own custom string interpolation behavior,