A Deep Dive into Building Dynamic Strings in C#

Jamie Burns
13 min readJan 17, 2023

We’ll look at our various options, and compare each for readability, maintainability and performance.

Photo by Florian Krumm on Unsplash

Writing text (or strings) in C# is easy.

string text = "hello";

It’s something that most C# developers will do every day. And most of the time we don’t need to think about it too much.

However, what happens if we need to insert some dynamic data into that string? Something like building a message that includes the number of items in a list, for example “You have 3 messages”.

That’s where this can get interesting, and in all my years of writing and reviewing code, I’ve seen countless ways that this has been done — some good, some bad, and some absolutely terrible.

Frequently, this comes down to using the right tool for the right job; recently I was struggling to find a decent way of writing a JSON string within a unit test so that it was clear what the data was, but without the pain of having to delimit all the quotes and braces. It was this that led me to find out about Raw String Literals (not sounding familiar? Read on!), which was a much better solution for me to use in these tests than my previous attempts using string interpolation.

--

--

Jamie Burns
Jamie Burns

Written by Jamie Burns

Software Engineer, founder of Bungalow64 Technologies