Comments

C# 6 features that help you write cleaner code

There have been many improvements to C# 6 that simplify your code. Unlike the features introduced in previous versions of C# (e.g. generics, LINQ, async programming, etc), these features are not revolutionary. But they’ll help you write cleaner and less-cluttered code.

In this post, I’ll delve into the details of these new features.

Auto-property Initializers

One of the things that always bugged me about properties in C# is that we couldn’t initialize them directly, like fields. We had to create a constructor to set them:

public class Post 
{
    public DateTime DateCreated { get; private set; }
    public Collection<Comment> Comments { get; private set; }

    public Post()
    {
        DateCreated = DateTime.Now;
        Comments = new Collection<Comment>();
    }
}

With C# 6, we can directly initialize a property without the need to create a constructor:

public class Post 
{
    public DateTime DateCreated { get; private set; } = DateTime.Now;

    public Collection<Comment> Comments { get; private set; }
       = new Collection<Comment>();
}

This is especially useful in initializing collections.

Dictionary Initializers

Before C# 6, we could initialize a Dictionary using the { key, value } syntax:

var dictionary = new Dictionary<string, string>
{
     { "LAX", "Los Angeles International Airport" },
     { "MEL", "Melbourne Tullamarine Airport" }
};

While this syntax works fine, if you’re initializing complex objects with nested structures, all these curly braces get in the way and you may easily lose track of them.

C# 6 introduces a new index-like syntax to initialize dictionaries:

var dictionary = new Dictionary<string, string>
{
     ["LAX"] = "Los Angeles International Airport",
     ["MEL"] = "Melbourne Tullamarine Airport" 
};

With this syntax, the extra noise due to curly braces is gone. Plus, keys stand out a bit more.

String Interpolation

This one is a simple but very effective improvement in C# 6 that I love. How many times have you used the String.Format() method like this:

var title = String.Format("{0} ({1})", post.Title, post.Comments.Count); 

While these placeholders make it easy to define a template, tracing them with their linked arguments causes a bit of distraction. Here, if you want to visualise the output, you have to look at the first placeholder ({0}), and then look at the first argument (post.Title). Then, you look at the second placeholder, and follow it up with the second argument. Your eyes keep moving from left to right.

C# 6 introduces a beautiful way to write the same code in a more direct way:

var title = $"{post.Title} ({post.Comments.Count})";

So, you need to prefix your string with $ and then you can replace placeholders with the actual arguments. Isn’t that cleaner?

Null-conditional Operator

This new syntax is my personal favorite and chances are it is going to be your favorite too! If you’ve been programming in C# for a little while, you should know that NullReferenceExpception is one of the most common exceptions that occur in .NET applications. Consider the following piece of code where we check for null:

var title = null;
if (post != null)
    title = post.Title;

How many times have you had to write code like this? We need to check an object for null before accessing one of its members. With C# 6, we can use the null-conditional operator to simplify this code as follows:

var title = post?.Title;

Here, if post is null, null will be returned and assigned to the title; otherwise, post.Title be assigned to the title variable.

So, what you put on the left side of the null-conditional operator will be evaluated for null. If it is null, null will be returned; otherwise, what you put on the right side of the null-conditional operator will be evaluated.

Here is another example of null-conditional operator using an indexer:

// Prior to C# 6
Post first = null;
if (posts != null)
    first = posts[0];

// C# 6
var first = posts?[0];

When using the null-conditional operator, we can access members in a chain:

// Prior to C# 6
if (post != null)
    body = post.Comments[0].Body.SubString(0, 100);

// C# 6
var body = post?.Comments[0].Body.SubString(0, 100);

We can also use the null-conditional operator multiple times in an expression:

// Prior to C# 6
var count = 0;

if (post != null)
{
    if (posts.Tags != null)
    {
        count = post.Tags.Count; 
    }
}

// C# 6
var count = post?.Tags?.Count;

There is something tricky about this last example. If either post or post.Tags is null, null will be returned; otherwise, post.Tags.Count will be returned. So, the data type for the count should be able to support both null and an int. So here, count is a nullable int (int?). If you want to define it as an int, you’ll need to add the null-coallescing operator at the end:

var count = post?.Tags?.Count ?? 0;

Another common use-case for the null-conditional operator is when triggering events. How many times have you seen code like this?

if (OnClick != null)
   OnClick(this, args);

We can re-write this code in C# 6 as follows:

OnClick?.Invoke(this, args);

So, if OnClick is null, nothing will happen; otherwise, the Invoke method will be called.

Getter-only Auto-Properties

How would you define a read-only auto-property in C#? Probably like this:

public class Post  
{
    public int Votes { get; private set; }
}

With this, you can only set the value of Votes from inside the Post class, but not from the outside. In C# 6, you can reduce the noise in your code by omitting the private set:

public class Post  
{
    public int Votes { get; }
}

Expression Bodied Members

Now we have a cleaner syntax for implementing properties or methods with a little bit of logic. Consider the following class:

public class Post  
{
    public int DaysOld 
    {
         return (DateCreated - DateTime.Today).TotalDays;
    }
}

In C# 6, we can use the => notation to immediately implement the getter for DaysOld property:

public class Post  
{
    public int DaysOld => (DateCreated - DateTime.Today).TotalDays;
}

So, no need for curly braces or the return keyword, which means less noise in the code.

You can use this syntax to implement simple methods as well:

public class Post  
{
    public int GetDaysOld() => (DateCreated - DateTime.Today).TotalDays;
}

Using Static

I’m not really a fan of this feature but thought to add it here to keep the post comprehensive. Consider this code snippet:

using System;

public class Program
{
    public static void Main()
    {
        Console.WriteLine("Hello World");
    }
}

With C# 6, you can import static classes into your using statements:

using static System.Console;

Note the use of static keyword after using.

With that, you can call the WriteLine method without prefixing it with its class name:

public class Program
{
    public static void Main()
    {
         WriteLine("Hello World");
    }
}

Is this code better? I let you be the judge of that. But personally, I see this as a backward step in C# 6. It is making it look more like Visual Basic, and I’m talking about the old Visual Basic, not even VB.NET! It can be a slight clean up if you have a static utility class and you’ve referenced its members in a file quite a few times. With this, yes for sure, you can remove the class name repeated a few times all over the place.

Summary

In case you love cheat sheets, I’ve put together all these tiny improvements in a simple PDF for you to remember and include in your programming toolbox. Some of these features, although useful, may require a little getting used to. But perfection comes with practice!

Download C# 6 Cheat Sheet

Related Posts

Tags: ,

8 responses to “C# 6 features that help you write cleaner code”

  1. Oscar says:

    very nice Mosh, Thanks

  2. Claudio says:

    Thanks a lot! I didn’t know about this features! They will be soon applied on my project!
    Nice work!

  3. Nice post! The “Getter-only Auto-Properties” part misses an important point, though; properties with private setters are backed by a mutable field, while a getter-only property is backed by a readonly field. This means that a getter-only property is truly immutable, and can only be set in the constructor (or using auto-property initializers), while a property with a private setter can be mutated inside the class.

  4. Lasantha says:

    This is awesome Mosh. Can’t imagine any nicer way to summarise these facts!

  5. Steve says:

    One use case of ‘using static’ that you don’t mention is that it allows you to be more precise for bringing in extension methods into a namespace.

    In C# 5, all extension classes in a namespace are automatically available to all classes that can see that namespace. With C# 6 you can do a ‘using static’ on a specific extension class to help limit the noise in the intellisense for extension methods.

  6. lsg says:

    String Interpolation – looks like taken from PHP.

  7. Steven Hansen says:

    Null propagation is amazing – I actually ran into it while taking your course, visual studio was correcting me and I wasn’t sure why your code was different – and wondered if all of the if/null statements could be simplified, the answer came with the C# 6 changes fortunately!

    Thanks for the great classes Mosh, I’ve done all 3 C# from basics to advanced, and I plan on doing faster coding, clean code, entity framework, and ASP.NET MVC courses.

    Do you plan on uploading your Full-Stack course onto Udemy?

Leave a Reply