Verbatim strings and string interpolation

Verbatim strings and string interpolation

There have always been a few different ways of dealing with strings of text in C#, depending on what we need we might use any of the following;

string normalString = "This is a string, to include a line break we need to escape it like this \n so it doesn't terminate the string";

string verbatimString = @"This is a verbatim string where we can type enter
and the string contains the line break";

If we want to include variables in our string we have a few options again;

int x = 5;

string concatenation = "We can do this " + x " to include the variable";

string format = string.Format("We can do this {0} to include the variable", x);

string interpolate = $"We can do this {x} to include the variable";

The two interesting ones here are verbatim and interpolated strings.
If we need to build a multiline string with variables, perhaps from a template we can combine them like this.

var name = "Simon";
var templateName = "How to interpolate a verbatim string";
var now = DateTime.UtcNow;

var output = $@"Hi {name},
This template is a demo of {templateName}.

It was ran at {now.ToString("o")}";

The output of the above demo is

Hi Simon,
This template is a demo of How to interpolate a verbatim string.

It was ran at 2017-04-11T14:46:09.5032168Z

For populating large multiline templates the ability to combine string interpolation with the formatting of verbatim string can be extremely useful

Share Tweet Send
You've successfully subscribed to
Great! Next, complete checkout for full access to
Welcome back! You've successfully signed in
Success! Your account is fully activated, you now have access to all content.