C# 6 & 7 features

by Admin 5. January 2017 09:39

C# 7.0 features

https://blogs.msdn.microsoft.com/dotnet/2016/08/24/whats-new-in-csharp-7-0/


C# 6.0 features

Roslyn, a new compiler introduced in C# 6.0. 

8 useful features in C# 6.

1.Auto Property Initializers

2.using static

3.Null Conditional Operator

4. Exception Filters

5. await in Catch and Finally block

6. index initializers

7. Expression Bodied functions

8. String Interpolation

 

1. Auto Property Initializers

It allows you to set an initial value for auto initializer. In earlier C# version this feature was not available.

Below is the code snippet.

 public class Customer

    {

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

    }

2. using static

It allows you to import the static methods of a single class.

for eg -instead of writing using System;

We can now write.

using static System.Console;

using static System.Math

See below code snippet.

using static System.Console;

            //Before C# 6.0

            Console.WriteLine("Hello");

            //After C# 6.0

            WriteLine("Welcome to C#"); 

            ReadLine();

 

3. Null-Conditional Operator

NULL Reference error always threatens to the developer. In C# 6.0 new version life is easy and it doesn't throw NULLReferenceException error.

            Product objProduct = new Product();

            if (string.IsNullOrEmpty(objProduct.ProductName))

            {

                objProduct = null;

            }

            // Before C# 6.0

            WriteLine(objProduct != null ? objProduct.ProductName : "Old Product"); 

            // from C# 6.0 onwards

            WriteLine(objProduct?.ProductName ? ? "New Product"); 

           public class Product

          {

              public string ProductName { get; set; } = string.Empty;

           }

 

4. Exception Filter

Exception filter allows you to show/log different exception messages based on your choice or requirement.

For eg - You want to show different exception messages to your internal and external users. How you will achieve this. Before C# 6.0 it was not possible, but now in C# 6.0, this feature allows you to do the same.

            string user1 = "user";

            string user2 = "admin";

            string loggedinUser = string.Empty;

            try

            {

                if (loggedinUser == admin)

                {

                    //Some action

                    //Exception occurred

                }

                else

                {

                    //Some action

                    //Exception occurred

                }

            }

            catch(Exception ex) when(loggedinUser == admin) // exception for admin

            {

                WriteLine("Admin related handling to be done.");

            }

            catch(Exception ex)all other users

            {

                WriteLine("Please contact admin / support");

            }

 

5. await in catch and finally block

Asynchronous programming in catch and finally

This is the most awaited feature. Before c# 6.0 it was not possible to use async and await within catch and finally block. But now it is possible in C# 6.0. 

        //Asynchronous programming in catch finally

        public async void CalCDevision(int val1, int val2)

        {

            try

            {

                int res = val1 / val2;

                WriteLine(res);

            }

            catch (Exception)

            {

                await CatchMethod();

            }

            finally

            {

                await FinallyMethod();

            }

        }

        private async Task CatchMethod()

       {

            WriteLine("Exception occured");

        }

        private async Task FinallyMethod()

        {

            WriteLine("Finally Executed");

        }

 

6. Index Initializer

This feature makes collection initializers more consistent.

Before C# 6.0 Dictionary Initialization syntax is {"Key", "Value"}

But now in C# 6.0 we can write like this - ["Key"] = "Value";

           //Dictionary initialization Before C# 6.0

             var WebPageError = new Dictionary<int, string> {

            { 404, "Page Not Found" }, { 301, "Moved Permanently" },{ 404, "Internal Server Error" }};

 

           //After C# 6.0

            var webPageError = new Dictionary<int, string>

            {

                [404] = "Page Not Found",

                [301] = "Moved Permanently",

                [500] = "Internal Server Error"

            };

 

7. Expression-Bodied Function

This feature allows us to write a function as an expression. See below code snippet and you will notice the differences.

       //Before C# 6.0

        public static int AddNumbers(int x, int y)

        {

            return x + y;

        }

        //C# 6.0 onwards

        public static int Add2Numbers(int x, int y) => x + y;

 

8. String Interpolation

With this new feature of C# 6.0 way to write Format string has been completely changed.

          string message = "Hi {0}.";

         string userName="Sample User";

          //Before C# 6.0

          string output = string.Format(message, userName);

          WriteLine(output);

 

          //C# 6.0

          message = $"Hi {userName}";

          WriteLine(message);

          ReadLine();

Tags:

Comments are closed

TextBox

Tag cloud

    RecentPosts