DEV Community

Simon Reynolds
Simon Reynolds

Posted on • Originally published at simonreynolds.ie on

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";
Enter fullscreen mode Exit fullscreen mode

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";
Enter fullscreen mode Exit fullscreen mode

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")}";
Enter fullscreen mode Exit fullscreen mode

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

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

Top comments (0)

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay