Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save JoseGonzalez321/0ea5e978867325bf0160a3990ecb0a97 to your computer and use it in GitHub Desktop.
Save JoseGonzalez321/0ea5e978867325bf0160a3990ecb0a97 to your computer and use it in GitHub Desktop.
Blog post multiline string literal

How to interpolate a multiline string literal

One of my favorite features of C# 6 is string interpolation. It helps move unnecessary string.format(...) noisy code.

String Interpolation

Here's a quick example:

var person = new Person {FirstName = "Jose", LastName = "Gonzalez"};
var name = string.Format("My name is {0} {1}", person.FirstName, person.LastName);

With C# 6 string interpolation becomes

var name = "My name is {person.FirstName} {person.LastName}";

I admit this is a trivial example. But you can already see the code readability and terseness. Less code means less time spent reading code.

But let's kick up a notch!

Interpolate a multiline string literal

There are times when you encounter code that has either a long string concatonation using +s or a StringBuilder (if you are lucky!). It gets fun when you have the embedded String.Format(...). I find this a common pattern in older code bases when executing a sql statement in code.

Enough talk. Let's look at some code.

public void GetData(int customerId, string businessCode)
{
	StringBuilder query = new StringBuilder();

	query.AppendLine("SELECT c.*");
	query.AppendLine("FROM   Customer c");
	query.AppendLine("INNER JOIN Business b ON c.BussinessCode = b.BussinessCode AND c.CustomerId = b.CustomerId");
	query.AppendLine("WHERE  c.customerId = " + customerId + "");
	query.AppendLine("AND    b.businessCode = '" + businessCode.ToString() + "'");

    //Do all the grunt work
	ExecuteQuery(query.ToString());
}

The code is too noisy.

Let's improve it.

Combine the string interpolation symbol $ with the @ verbatim literal symbol and get the following:

public void GetData(int customerId, string businessCode)
{
    var query = 
        $@"SELECT c.*
           FROM  Customer c
           INNER JOIN Business b ON c.BussinessCode = b.BussinessCode AND c.CustomerId = b.CustomerId
           WHERE c.customerId = {customerId}
           AND   b.businessCode = '{businessCode}'";

    //Do all the grunt work
    ExecuteQuery(query);
}
  • The intend of our code becomes more relevant.
  • Less noisy / cleaner code.
  • Less code to read.

Conclusion

Use string interpolation to replace those annoying String.Formats.

Combine string interpolation and string literal $Q to create multiline string literals. It's a sweet and powerful combination to help you clean up your code.

Resauces

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment