How to Interpolate a Multiline String Literal

One of my favorite features of C# 6 is string interpolation. It helps move unnecessary string.format(...) noisy code.

String Interpolation

Here’s a quick example:

I admit this is a trivial example. But you can already see the code readability and terseness. Less code means less time spent reading code.

Interpolate a multiline string literal

Let’s kick up a notch!

There are times when you encounter code that has either a long string concatonation using +s or a StringBuilder (if you are lucky!). It gets fun when you have the embedded String.Format(...). I find this a common pattern in older code bases (e.g. executing a sql statement in code).

Enough talk. Let’s look at some code.

I find this code way too noisy for what’s doing.

Let’s improve it.

Combine the string interpolation symbol $ with the @ verbatim literal symbol and get the following:

  • The intend of our code becomes more relevant.
  • Less noisy / cleaner code.
  • Less code to read.

Conclusion

Use string interpolation to replace those annoying String.Formats.

Combine string interpolation and string literal $@ to create multiline string literals. It’s a sweet and powerful combination to help you clean up your code.

Where else can you use this powerful combinarion S@?

Helpful resources

  • It’s not the point of the post and the point still stands and $@ is nice and worthy of an example – but this example is code prone to SQL Injection. This is not code you’d actually want to use. Something that needs to be said here.