Getting started

edit

Install the package

Add the Meziantou.Framework.FixedStringBuilder package to your project:

dotnet package add Meziantou.Framework.FixedStringBuilder

The types are in the Meziantou.Framework.FixedStringBuilder namespace. The examples of this documentation omit the using directives, and check their results with assertions such as Assert.Equal.

Choose a capacity

TypeMaximum number of characters
FixedStringBuilder88
FixedStringBuilder1616
FixedStringBuilder3232
FixedStringBuilder6464

Choose the smallest type that fits the longest value: every value has the size of its capacity, whatever its length. For another capacity, generate your own type.

Create a fixed string

Assign a string, or an interpolated string, to a variable of the type. The interpolated string is written directly into the struct, without creating a string first, and you can append more text afterwards:

FixedStringBuilder16 sb = $"Hello {"World"}";
sb.AppendLiteral("!");

string str = sb.ToString();
Assert.Equal("Hello World!", str);

ToString() creates the string. Call it only when an API needs a string: comparisons, spans and formatting work on the struct directly. See Working with fixed strings.

Next steps