C# 6.0 new features2 min read

With C# 6.0 we got new features which are not revolutionary but nonetheless are pretty handy improvements that helps us simplify our code.

So let’s list these new features:

  • Using Static
  • Expression Bodied Members
  • Getter-only Auto-Properties
  • Auto-property Initializers
  • Dictionary Initializers
  • Null-conditional Operator
  • String Interpolation

Using Static

We can import static classes with using statemens:

i.e. If we have some Foo class with static method Bar, we can write the following code:

using static Foo

and then we can write our code like:

public class Program {
    public static void Main() {
         Bar("Foo.Bar.Example");    
}
}

Expression Bodied Members

With this new feature we use “=>” notation to implement getters right away. We can also implement simple methods aswell.

i.e.:

 
public class OrderedItem  {   
  public int DaysSinceOrder => (OrderCreated - DateTime.Today).TotalDays;
}


Getter-only Auto-Properties

With this new feature we can reduce code by not using private set when defining read-only auto-property.

i.e.:

public class Item  {
    public int Rate { get; }
}

Auto-property Initializers

This one helps us with initialization without the need for creating a constructor.

i.e.:

public class Order
{
public DateTime OrderCreated { get; private set; } = DateTime.Now;
public Collection OrderItems { get; private set; } = new Collection();
}

Dictionary Initializers

This feature gives us  index like syntax for dictionaries initialization, hint: no more curly braces.

i.e.:

var names = new Dictionary
{
["DJ"] = "Denis Jakus",
["FL"] = "First Name, Last Name"
};

Null-conditional Operator

This one is definetly the most usefull and by far my favorite. It’s used to check for NullReferenceException, swift alike syntax which is also very handy when dealing with triggering events.

i.e.:

var firstName = user?.FirstName; // if user is not null return user FirstName 

or

OnClick?.Invoke(this, args);

String Interpolation

My second favorite feature is this one used for concatenating strings. No more need to use String.Format.

Just use “$” in front of quotations and user curly braces to use object properties. Much simpler and cleaner!

i.e.:

var fullName = $"{user.FirstName} {user.LastName}";

SUMMARY

As you can see, these are non revolutionary features but can greatly improve readability and make our code much cleaner.

Leave a Reply

Your email address will not be published. Required fields are marked *