Sunday 27 September 2015

What's New in C# 6.0


C# 6.0 has not introduced any new concepts like other versions of C# but instead it introduced some of very interesting and useful features which will help you to write more clean code with less typing.
I am sure as a developer you are going to love these features. Lets figure out what are those:



1. Getter-only auto Property.
 C# 6.0 allows you to define getter-only property and initialize it as part of constructor or directly.

class Features
{
        public string FirstName { get; }
        public string LastName { get; } = "Mahto";
        public Features()
        {
            FirstName = "Binod";
        }
}

2. Using static members: Use static with using directive for namespace reference.
It allow you to access static members of a type without having to qualify the access with the type name,

using static System.Math;

and now when you need to call say Sqrt, you don't need to write Math.Sqrt(...) instead just write Sqrt(...).
using CSharp6Features2.Day; //Here Day is an enum which I have defined.

so next time I don't need to specify Enum type 'Day' while calling it's property.

3. String interpolation: Get rid of using value tokens with "string.Format" to format string.
Example: Old way:

string fName = "Binod", lName = "Mahto";
Console.WriteLine(string.Format("My name is {0} {1}", fName, lName));

in C#6.0

string fName = "Binod", lName = "Mahto";
Console.WriteLine($"My name is {fName} {lName}");

4. Expression-bodied properties: Convert your methods or properties which returns data based on some calculation, to one line code like property using lambda expression.
for example:
Old way:
private double GetFullName(string fname, string lname)
{
         return fname + " " + lname;
}

in C# 6.0
public string FullName => $"{fname} {lname}";




5. Index Initializers: C# 6.0 has extended the object initializers to allow to set values to keys through any indexer that the new object has.
Example: Old Way:
public JObject ToJson()
{
       var obj = new JObject();
       obj["X"] = "Binod";
       obj["Y"] = "Mahto";
       return obj;
}

in C#6.0:
public JObject ToJson()
{
       var obj = new JObject() {["FName"] = "Binod",["LName"] = "Mahto" };
       return obj;
}
OR
public JObject ToJson() => new JObject() {["FName"] = "Binod",["LName"] = "Mahto" };

6. Null-conditional operators(?): It helps to avoid lot of codes which we write while accessing objects, like do null check for objects then do null check of that objects properties and so on. Let see the example:
Old way:
 public string FromJson(JObject json)
{
        if(json != null &&
            json["FName"] != null &&
            json["FName"].Type == JTokenType.String &
            json["LName"] != null &&
            json["LName"].Type == JTokenType.String)
         {
              return $"{json["FName"]} {json["LName"]}";
         }
         return string.Empty;
}

in C# 6.0
 public string FromJson(JObject json)
{
     if (json?["FName"]?.Type == JTokenType.String &&
          json?["LName"]?.Type == JTokenType.String)
     {
           return $"{json["FName"]} {json["LName"]}";
      }
      return string.Empty;
}

it is also very useful to do the event null check before triggering the event.
Ex: OnChanged?.Invloke(this, args);
in this case event will be triggered only if event is not null.

7. The nameof operator: There are scenarios when we need to know the name of program elements (property/parameter name), specially while throwing exceptions.
private static int Calculate(ABC obj)
{
       if (obj.y == 0)
            throw new DivideByZeroException(nameof(obj.y));
       else
           return obj.x / obj.y;
}

At last, this is the feature which I noticed in Visual Studio 2015 which impressed me a lot.
Your visual studio itself will let you know about some tips to clean your code (as Resharper does)
Ex: namespace references in using directive  which are not used. There are lot many, I am sure these features you are going to love it.

Till now I haven't encountered any such scenarios where I need the use of nameof operator.

That's it.

Thank You for reading. Feel free to give your feedback/comment.


No comments:

Post a Comment