C# has been improved greatly over the years with useful features that have increased productivity for developers.
Below I’ll explain a few of my favorite features.
String Interpolation
In many programming languages, writing a string with embedded variables can be cumbersome. The longer the string, the more noise is added affecting readability like so:
C# 6.0 introduced a new string interpolation feature in which the variables can be written as expressions without the need for awkward string concatenation:
This results in the same output, but the code is much easier to read and maintain. To use this feature the string must begin with the $ symbol . String formatters may also be applied as shown in the
Score
variable.As a plus – expressions will be highlighted within the whole string for better visibility in Visual Studio.
Expression-bodied function members
If you’ve created a few C# POCO classes over the years, I’m willing to bet many of the properties you’ve written are single read only statements.
Here’s a typical example where
FullName
is a read only property:...And now here’s the same example using the
FullName
property as an expression-bodied function member:The output is identical to the previous example. The code has been compacted down to one line, reducing noise.
Null-conditional operators
Null checking is an important subject for producing stable apps. Until now, null checking has often been verbose. Here’s a typical null checking statement combined with a ternary operator:
With C# 6.0 null checking becomes more succinct:
In this example the variable
firstName
is assigned null if the person object is null. If the person object is not null, the value of theFirstName
property will be applied. This works thanks to the?
operator.But what if we want to supply a substituted value for null values, similar to the ternary operator approach?
This can be solved by using the null coalescing operator:
Here, the expression always returns a string. The rules of the
?
operator ensure that the left-hand side of the operator is evaluated only once.
Happy Coding 🤓
Top comments (0)