shallow focus photography of keychains

Awesome String Interpolation with C# 2020

In the wonderful programming language of C#, there‚Äôs a number of ways of adding variables into strings. In this post, we’ll describe how to use the String Interpolation with C# that was added in .net 6.

Adding variables into strings

As a developer, you frequently find yourself adding variables into strings. Whether this is for printing out text, return messages, or writing to a file, there are a hundred reasons why you’d want variables added to a string. There were two main ways you’d add variables into a string before c#6 was released.

Below we’ll look at a couple of these examples and discuss the pitfalls.

var intValue = 1;
var doubleValue = 1.0;
var stringValue = "hello";
var formattedString = String.Format("Integer value {0}. Double value {1}. String value {2}", intValue, doubleValue, stringValue);

var concatenatedString = "Integer value" + intValue + ". Double value" + doubleValue + ". String value " + stringValue;

In the above code snippet, you can see we’ve used two approaches to adding variables to a string. These are:

  • Formatting, which replaces out each of the variables in the string. This uses an array of objects passed into the formatter to identify which variable goes where.
  • Concatenation. Which uses “+” characters to join together strings and variables.

Firstly, both of these approaches are a little messy and hard to read. Secondly, they’re difficult to edit without breaking the string.

String Interpolation with C#

This is where String Interpolation comes in!

var stringInterpolation = $"This is my integer value {intValue}. This is my double value {doubleValue}. This is my string value {stringValue}";

In the example above, you can see interpolation is in use by the “$” character at the start of the string. Switching on interpolation lets you slot the variables directly into the string surrounded by curly brackets. This gives you a simple, readable approach to string concatenation!

In conclusion, this is a great way of formatting strings that’s easy to read and understand!

There’s a lot more that can be done with string interpolation in the dot net framework, and I’d strongly recommend reading through Microsoft’s documentation here.

Leave a Comment

Your email address will not be published. Required fields are marked *