Thursday 7 April 2016

C# 6.0 New Features


C# 6.0 Features we have discussed some of the interesting features as like auto property initializations, Expression bodied function, static class uses and string interpolation method. In this post I write about C# 6.0 new features.


1. Import of static type members into namespace

If we want to print something to the Console static method we are using following line of code in c# 5.0 version.


using System;

namespace CProgram
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");
        }
    }
}


With C# 6.0 you can write using static qualifier and reference the System.Console;


using static System.Console;

namespace CProgram
{
    class Program
    {
        static void Main(string[] args)
        {
            WriteLine("Hello World!");
        }
    }
}



2. Await in catch/finally/blocks

In c# 6.0 you can write asynchronous code inside in a catch / finally block. This will help developers as they often need to log exception to a file or database without blocking the current thread.


using System;
using System.Net.Http;
using System.Threading.Tasks;
using static System.Console;


namespace CProgram
{
    class Program
    {
        static void Main(string[] args)
        {
            Task.Factory.StartNew(() => GetPage());
            ReadLine();
        }

        private async static Task GetPage()
        {
            HttpClient client = new HttpClient();
            try
            {
                var result = await client.GetStringAsync("http://www.telerik.com");
                WriteLine(result);
            }
            catch (Exception exception)
            {
                try
                {
                    //This asynchronous request will run if the first request failed. 
                    var result = await client.GetStringAsync("http://www.devgohel.com");
                    WriteLine(result);
                }
                catch
                {
                    WriteLine("Entered Catch Block");
                }
                finally
                {
                    WriteLine("Entered Finally Block");
                }
            }
        }
    }
}



3. Auto Property Initializers

In the C# later version we are using properties with getter and setter and initialized our constructor.


using System;

namespace CProgram
{
    class Program
    {
        static void Main(string[] args)
        {
            Customer cust = new Customer();
            Console.WriteLine(cust.customerID);
            Console.ReadLine();
        }
    }

    public class Customer
    {
        public Customer()
        {
            customerID = Guid.NewGuid();
        }

        public Guid customerID { get; set; }
    }

}

In C# 6.0 modify the property intializers with inline initialization.


public class Customer
    {
          public Guid customerID { get; set; } = Guid.NewGuid();
    }



4. Expression bodied members

Function and properties in lambda expressions save us from defining our function and property statement block.


using static System.Console;

namespace CProgram
{
    class Program
    {
        private static double MultiplyNumbers(double num1, double num2) => num1 * num2;

        static void Main(string[] args)
        {
            double num1 = 5;
            double num2 = 10;

            WriteLine(MultiplyNumbers(num1, num2));
            ReadLine();
        }
    }
}



5. Null propagator

Null conditional operator is very useful may be all developer hates NullReferenceException errors.  Using “?.” to check if instance is null or not. The code listing below will print the person .Name field if one is supplied or will print “Field is null” if one isn't supplied.


using System;
using static System.Console;


namespace CProgram
{
    class Program
    {
        static void Main(string[] args)
        {
            Customer Cust = new Customer();
            if (Cust.Name == Cust.Empty)
            {
                Cust = null;
            }

            WriteLine(Cust?.Name ?? "Field is null.");

            ReadLine();
        }
    }

    public class Person
    {
        public string Name { get; set; } = "";
    }
}



6. String interpolation

In C# later version we typically concatenated two or more strings together with one of the following methods


using System;

namespace CProgram
{
    class Program
    {
        static void Main(string[] args)
        {
            string Ex1 = "Michael";
            string Ex2 = "Crump";

            Console.WriteLine("Name : " + Ex1 + " " + Ex2);
            Console.WriteLine("Name : {0} {1}", Ex1, Ex2);

            Console.ReadLine();
        }
    }
}

Now using c# 6.0 we have a cleaner format a string by writing own argument instead of referring to them as placeholders. Just use $ before the start of string.


WriteLine($"{Ex1} {Ex2} is my name!");

C# automatically know Ex1 and Ex2 variable and put their respective values.



7. Nameof operator

The nameof operator allows developers to use a program element as text. Now we can specify any string literals directly with the nameof operator. It can be used to create name of expression to specify the name where expression may be a property-group or a method-group.


static void DisplayName ( string name )   
{   
  if (name== null)   
  throw new ArgumentNullException(nameof(name));   
}   

Dictionary intializer

In c# later version you would initialize the Dictionary with a {“Key”, “Value”} using Dictionary<K,V> syntax.

using System.Collections.Generic;

namespace CProgram
{
    class Program
    {
        static void Main(string[] args)
        {
            var stars = new Dictionary<string, string> ()
            {
                 { "Example 1", "Basketball" },
                 { "Example 2", "Football" }
            };

            foreach (KeyValuePair<string, string> keyValuePair in stars)
            {
                Console.WriteLine(keyValuePair.Key + ": " +
                keyValuePair.Value + "\n");
            }

            Console.ReadLine();
        }
    }
}


In c# 6.0 you can place the key between two square brackets [“Key”] and then set the value of the key [“Key”] = “Value”. It reduces the amount of errors which is old way produced.


using System.Collections.Generic;
using static System.Console;

namespace CProgram
{
    class Program
    {
        static void Main(string[] args)
        {
            var stars = new Dictionary<string, string> ()
            {
                ["Example 1"] = "Basketball",
                ["Example 2"] = "Football"
            };

            foreach (KeyValuePair<string, string> keyValuePair in stars)
            {
                WriteLine(keyValuePair.Key + ": " +
                keyValuePair.Value + "\n");
            }

            ReadLine();
        }
    }
}



I hope you like this post. if you share like and comments to this post it is encourage me write more respective articles related to .Net developers. 

No comments:

Post a Comment