How to use a $ symbol to introduce a string expression, and fill in the blanks
Introduced in Visual Studio, string interpolation allows you to linking different C# expressions contained in curly parentheses, with everything preceded by a dollar sign. This blog explains how to use this handy new short-cut.

Posted by Andy Brown on 22 December 2017

You need a minimum screen resolution of about 700 pixels width to see our blogs. This is because they contain diagrams and tables which would not be viewable easily on a mobile phone or small laptop. Please use a larger tablet, notebook or desktop computer, or change your screen resolution settings.

The new string interpolation feature in C# to build strings

Following a course this week (thanks Garry et al) I realised that we had overlooked a new feature introduced in Visual Studio 2015.  Suppose you want to display a message like this:

Concatenating strings

When you click on OK in this simple form, you want to display the message shown by joining the 3 bits of text together.

 

There are many ways to do this, the simplest two of which are probably to use a string builder, or just to use the + sign:

string firstName = txtFirst.Text;

string lastName = txtLast.Text;

string company = txtCompany.Text;

MessageBox.Show(

firstName + " " +

lastName + " works for " +

company);

However, there is now an easier way which allows you to apply a formatting string:

string firstName = txtFirst.Text;

string lastName = txtLast.Text;

string company = txtCompany.Text;

string message =

$"{firstName} {lastName} works for {company}";

MessageBox.Show(message);

What the application will do is substitute in the value of any expression in curly brackets {}.  Here I've just used variables, but I could use almost any C# expression.  For example this property would combine the text entered in the form to give someone's full name:

private string fullName

{

get

{

// returns someone's full name

return $"{txtFirst.Text} {txtLast.Text}";

}

}

You could then refer to the value of this property in another string expression:

string firstName = txtFirst.Text;

string lastName = txtLast.Text;

string company = txtCompany.Text;

string message =

$"{fullName} works for {company}";

MessageBox.Show(message);

All very clever - now I just have to remember this new way of doing things! 

This blog has 0 threads Add post