C# 6.0 New Features - String Interpolation

dev csharp

One of favorite features is the new string formatting using String Interpolation. In the past I encountered a lot of errors while formatting strings especially when preparing log messages. You may need lots of small pieces of data that so after a few iterations you may forget to add new parameters.

For example in the imaginary Log method below only 3 parameters are supplied whereas the string expects 4. It compiles successfully because the string is generated at run-time and it doesn’t check the number curly braces against the number of parameters supplied.

Argument count mismatch error

Using the new feature such errors can be avoided as we can put the values directly in their places in the string:

public class StringInterpolation
    public string Log(string timestamp, string application, string error, string status)
        return string.Format("[Timestamp: \{timestamp}], Application: [\{application}], Error: [\{error}], Status [\{status}]");

No more parameter mismatch errors!