Read our blogs, tips and tutorials
Try our exercises or test your skills
Watch our tutorial videos or shorts
Take a self-paced course
Read our recent newsletters
License our courseware
Book expert consultancy
Buy our publications
Get help in using our site
547 attributed reviews in the last 3 years
Refreshingly small course sizes
Outstandingly good courseware
Whizzy online classrooms
Wise Owl trainers only (no freelancers)
Almost no cancellations
We have genuine integrity
We invoice after training
Review 30+ years of Wise Owl
View our top 100 clients
Search our website
We also send out useful tips in a monthly email newsletter ...
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. |
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:
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!
Some other pages relevant to the above blog include:
Kingsmoor House
Railway Street
GLOSSOP
SK13 2AA
Landmark Offices
99 Bishopsgate
LONDON
EC2M 3XD
Holiday Inn
25 Aytoun Street
MANCHESTER
M1 3AE
© Wise Owl Business Solutions Ltd 2024. All Rights Reserved.