Dev Log 002: C# + String Interpolation
The Dev Log contains tips and tricks that I have found through my personal coding projects and experiments. As I find out new things, learn new tricks, I’ll share them here to help you with your own coding projects! You can follow me at LinkedIn, or on Twitter under @sfdesigner.
Some of the best features of C# 6 are shortcuts that are added to make coding faster and more reliable. I often am working with strings and combining variables within strings for display in apps. With C# 6, you can use a simple dollar sign to create a string that can combine variables, called interpolation. When you use this format, any variable that you weave into the string will access it’s ToString method if it has one and builds the string for you.
Code Link
I posted it as a Gist that you can access here:
Description
The first example is the simplest. It creates a string variable and assigns it an interpolated string with a single variable. To create the string, you first start with a dollar sign ($) then you begin your string with the quotation marks. You then define the location for where the variable will be using curly braces and then put the variable name within it.
The second example shows how you can perform the interpolation directly inside a method without needing to create a new temporary string variable--which is a big time saver and shortcut!
In the third example, you can perform evaluations in line with the variable insertion within the string.
You aren’t limited to a single variable as well. In the fourth example, you can place multiple variables in the interpolated string.
You can format the values using string formatters. The one that I probably would use the most would be the currency formatter. By adding a suffix to the variable reference after a colon, you can define the formatter and apply it to your value. In this case it uses currency or C, with 2 digits.
Finally, I was thinking of a way to format strings based on singular or plural names. The final example is a crude way to do this. It calls a static method that returns the right string to match the right singular or plural noun in the sentence.
There are a lot more formatters and other cool things you can do with the simplified $ syntax, I’ll be using this a lot more throughout my code.
Hope you can too!
Hi Doug, Nice post on C# 6 string interpolation. Your ReturnName() method reminded me of a Nuget package I saw before, called Humanizer and its ToQuantity() method (https://github.com/Humanizr/Humanizer#toquantity). The Nuget package might be too big for your sample code, but it has a lot of interesting, fluent APIs, which might be useful for other cases. Having said that, how you did it was quite okay (or you could simplify the if-else further with the ?: operator).
I love shortcuts that work in production! Thank you, Doug Winnie.