One of the new, and probably very unused capabilities of C# 6, is String Interpolation. Ok, that’s not really a new concept. We’ve seen it with String.Format() and the ideologically wrong String.Concat() methods.
Hell, we’ve probably all (at some point in our lives) done [string + ” ” + string] and made it work. Of course, not going into why that’s completely wrong, lets assume we’ve been using the String.Format() method most..
internal static string ReturnValue(TestObject x, TestObject y) { var orgExpression = String.Format("{0} in the year {1}", x.Name, y.Year); return orgExpression; }
Of course, a very simplistic design – but it shows the string interpolation (e.g. loosely translated [the method of which one point of data is created out of multiple points of data]).
With C# 6 we’re seeing something a bit niftier (and dare say I…neater?)
internal static string NewMethod(TestObject x, TestObject y) { var newExpression = $"{x.Name} in the year {y.Year}"; return newExpression; }
The biggest hassle with String.Format(); well aside from the fact that it’s somewhat error prone if you started to get a bit complex; you see, the order of the parameters are extremely important. Getting too smart here could get you into some serious trouble.
Plus, the new way of doing this is a lot more readable (read: maintainable)..
As in the “old” days with String.Format() we can still use format expressions.
internal static string NewMethod2(TestObject x, TestObject y) { var newExpression = $"{x.Name} in the year {y.Year:D4}"; return newExpression; }
We can even use conditional expressions if we need to.
internal static string NewMethod3(TestObject x, TestObject y) { var newExpression = $"{x.Name} in the year {(y.Year < 1 ? "AD 0" : "AD 2015")}"; return newExpression; }
I for one am very happy with the development of C# these days.
Have fun, stay safe and keep coding.