C# 6 – New features

C# 6 is the flavor of C# that ships with Visual Studio 2015.  I liked the fact that the enhancements in C# 6 focuses mainly on making the everyday coding scenarios simpler while keeping C# as a language lighter.

  1. static in using statements
    While creating console apps, it’s quite frequent that we use Console.Write(), Console.WriteLine(), Console.Read(), etc. With C# 6, you can keep the Console with the using statements and just use Write instead of Console.Write, WriteLine instead of Console.WriteLine and so on and so forth.
    Example –
    Add the following using statement:
    using static System.Console;
    You can do this for any static classes that you might be using in your project. This usage is not just limited to the console apps. It’s just that the Console example is a lot famous 😉
    We would normally have a static class with utility functions in our project. For example, Utilities.GetUserData. You can keep the Utilities with the using statements and happily use GetUserData in the code.
  2. Enums in using statement
    Just like we can import the static types with the help of using statement, we can also import enums.
    For example, instead of using DayOfWeek.Sunday, you could simply use Sunday and keep the DayOfWeek with the using statements.
    Now, when it comes to DayOfWeek enumeration, it makes sense to use the using static, but, not always will it make that much of sense. The wisdom is in deciding whether to use the using static or not.
  3. ReadOnly auto properties

    Prior to C# 6, if one had to create a readonly property, he/she had to create it as:

    public object UserContext { get; private set; }
    Or use a conventional way of creating properties with the help of backing fields, and initialize them with a value.

    But, with C# 6, you neither have to create a backing field nor you have to use the private set; All you need to do is:

    public object UserContext{ get; }
    Now, if you’re thinking how to initialize a property without a setter or a backing field, just remember how we do the initialization for readonly variables. Yes, you’re right! We can initialize these properties at the time of creating them or inside a constructor.
    Here’s how:
    public object UserContext { get; } = new { UserName = "domain\\username", Group = "Administrators" };
    Or
    public ProductData()
    {
    UserContext = new { UserName = "domain\\username", Group = "Administrators" };
    }
  4. Expression-bodied function members
    Expression-bodied function members allow methods, properties and other kinds of function members to have bodies that are expressions instead of statement blocks, just like with lambda expressions.
    For example:
    public double GetTotalCost(ProductData data) => data.Quantity * data.Rate;
  5. String interpolation
    String interpolation is introduced in C# 6 to simplify String.Format. I am not saying String.Format is bad. It’s great! But a little clunky and error prone. You have to number the placeholders and place the values in the right order. But, with string interpolation feature of C# 6, all that is simplified. Just use a $ sign before the starting a string and use the placeholders as the real variable places for values.
    Here’s an example:
    public string GetTotalCostStatement(ProductData data) => $"The total cost of the product \"{data.Name}\" is {data.Quantity * data.Rate}.";
    We all know that with String.Format, you would have to first number the placeholders and then pass the values in the correct order. This can become error prone when the number of placeholders are more or they are repeated for displaying a particular value more than once. But now, you need not worry about the placement of placeholders, you can place the variables directly within the curly brackets. Not only this, you can enjoy full intellisense support within the curly brackets.
  6. NULL conditional operator
    NULL conditional operator is the quickest way to perform a NULL check.
    For checking NULLs in the prior versions of C#, we used to do:
    var person = GetPerson(11579);
    if(person != null)
    {
    Console.WriteLine(person.FirstName);
    }

    Here’s how we do it in C# 6:
    Console.WriteLine(person?.FirstName);
    A little question mark helps us to get rid of those cluttered NULL check conditions.
  7. The nameof keyword
    Consider the following method:
    private static void GetPersonData(string personObject)
    {
    var fields = personObject.Split(',');
    foreach (var field in fields)
    {
    WriteLine($"personObject - {field?.Trim()}");
    }
    }

    Now what will happen if the name of the variable personObject is changed to just person?
    You will use the visual studio short-cut – Ctrl+. and quickly change all the occurrences of personObject to person. But the string “personObject” will stay unchanged. Because for the compiler, its just a string literal. Compiler isn’t aware of its business significance.
    For such scenarios, we can now use the nameof keyword. Here’s how:
    private static void GetPersonData(string personObject)
    {
    var fields = personObject.Split(',');
    foreach (var field in fields)
    {
    WriteLine($"{nameof(personObject)} - {field?.Trim()}");
    }
    }

Advertisements

One Comment Add yours

  1. Gunaprasad says:

    Nice article Finish😀

    Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s