loading...
Cover image for C# - Handy Features

C# - Handy Features

dalbirburhm profile image Dalbir Burhm ・2 min read

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:

Alt Text

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:

Alt Text

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:

Alt Text

...And now here’s the same example using the FullName property as an expression-bodied function member:

Alt Text

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:

Alt Text

With C# 6.0 null checking becomes more succinct:

Alt Text

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 the FirstName 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:

Alt Text

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 🤓

Posted on by:

dalbirburhm profile

Dalbir Burhm

@dalbirburhm

Dalbir is a .NET Developer (MCSD certified) based in the East Midlands, UK. Since the early 2000s he’s built web solutions and provided software consultancy to small and large blue-chip enterprises.

Discussion

markdown guide