Six practical features of C# 6.0 to use in your everyday coding

With this article I would like to present you six useful features of the 6.0 version of C#.

null conditional operator

Removes the need for checking for null values and thus we avoid the tedious if(... != null && ... != null ...) if conditions.

1
2
  if (myDog?.Mouth?.TeethsInMouth[0]?.ScientificName == "default tooth name") ...
  

Property initialization

Define and initialize a property at once. By doing this way, we do not have to initialize the property in the constructor of the class.

1
2
  public string ScientificName { get; set; } = "default tooth name";
  

Expression bodied methods

Use the following type of method declaration (lambda symbol) when dealing with “one line” methods.

1
2
  public int CalculateAgeOfDogAsAgeOfHuman() => this.age * 7;
  

static keyword in using

Use it for a static class when you referencing it inside another class. By doing that, when we call the members of the static class, we can call them directly without writing the name of the class.

1
2
  using static NewFeaturesInCSharpSix.ProgramHelper;
  

String interpolation

The $-sign form of using values from variables or properties inside strings is simpler and requires fewer code than the traditional String.Format.

1
2
  $"Dog's name: {this.name}, dog's age: {this.age}";
  

The nameof() function

Use this function if you want to print the name of a property or a field as a string:

1
2
3
  var test = "test it!";
  Console.WriteLine(nameof(test)); // "test" is getting printed in the console.
  

Take a look at this repository here where you can find working examples for the previous features.

comments powered by Disqus