Show / Hide Table of Contents

String Interpolation

String Interpolation Expression allows to simplify code generation associated with string formatting. This feature is powered by string interpolation in C# and VB.NET.

In Metaprogramming library, interpolated string expression is represented by InterpolationExpression class.

using DotNext.Linq.Expressions;
using static DotNext.Metaprogramming.CodeGenerator;

Lambda<Action<int, int>>(fun =>
{
	var (x, y) = fun;
	WriteLine(InterpolationExpression.PlainString($"Sum of {x} and {y} is {x.Add(y)}"));
});

//generated code is

new Action<int, int>(x, y => Console.WriteLine($"Sum of {x} and {y} is {x + y}"));

PlainString factory method converts interpolated string into expression node of type String. So, at runtime, it will be represented as a formatted string. Under the hood, the generated expression is a call to String.Format method.

FormattableString factory method converts interpolated string into expression node of type FormattableString. It can be helpful to change the culture of the string at runtime.

Create factory method converts interpolated string to a series of statements according to the transformation described in this article. This is the recommended way to express the interpolated string because it provides the best code generation quality. The generated code uses stack allocation and memory pooling to achieve zero heap allocation.

  • Edit this page
☀
☾
In this article
Back to top
Supported by the .NET Foundation
☀
☾