Friday, September 25, 2015

New features of C# 6.0 with implementation



We know that C# 6.0 has been shipped with .NET 4.6 framework in Visual Studio 2015. This supports Roslyn compiler. In this example we will understand new feature of C# and its practical usages. So, let’s start one by one.
     
     1)     Default property Initializer

Here is syntax for default property initialization of C# 6.0

    class myClass
    {
        public string Name { get; set; } = "Sourav";
    }

Earlier to initialize default property we need to write default constructor.  Now, we can initialize value in time of defining property. If class contains few property and if we want to initialize fewer of them with default value then this practice can give is clean code.

You may think that, why we need constructor further? If we can set value in time of property definition? We need constructor in time of injecting value to property.
     
     2)     Caller information for better debugging.

I believe this feature of C# can give better debugging and logging experiencing.
class myClass
    {
        public void Hello()
        {

        }
        public void Hi( [CallerMemberName] string name ="",
[CallerLineNumber] int line=0,
[CallerFilePath] string path ="")
        {
            Console.WriteLine("Name : " + name + "Line: " + line + "path: " + path);
        }
    }

We can log those information in normal audit log in application to check flow of application and movement of user’s behavior.

As per those information we may come in conclusion that from which function the current function is called most of the time.

     3)     Exception checking

This feature is extremely helpful to capture better exception in flow. Let’s consider below code snippet.
        
        public void myFunction()
        {
            string ConnectionString = null;
            try
            {
                ConnectionString = GetConnectionStringFromSomePlace();

            }
            catch (Exception ex) when(ConnectionString == null)
            {
                //log that Connection string is null
                throw;
            }
            catch
            {
                throw;
            }
        }

In this example, connection string is coming from some other function/location, it could be from another program / Database.

Now, in first catch we are checking whether connection string is null or not? If so, we can log/report to respective function with detail information.

     4)     await in Catch Block

This feature will really helpful if logging mechanism is in file system. We know asynchronous operation is really helpful for long running I/O bound task.

class myClass
    {
        public async Task LogException()
        {
            //Log in file system.
        }
        public async void myFunction()
        {
            try
            {

            }
            catch (Exception)
            {
                await LogException();
            }
        }
    }

So, application control need not wait to be finish of logging operation. It can immediately response user with proper error message and in background logging operation will perform which need to be synchronous with other operation.

     5)     Null checking of variable/property

From my previous experience, I can say that this is one big pitfall in code.

public string Show(string name)
        {
            Console.WriteLine(name.ToString());
        }

It will throw exception if name contains null value. So, to implement defensive code we need to check null before calling ToString() extension method or we have to use Convert.Tostring().
In C# 6.0 guys made thing easier,

Console.WriteLine(name?.ToString());

“?” will perform null checking and will not throw exception if name is null.

     6)     Improvement of syntax in Dictionary

Now, we can define Dictionary in following forms.

     Dictionary<int, string> user = new Dictionary<int, string>
            {
                [1] = "Sourav",
                [2] = "Kayal"
            };
           
     //another form
            Dictionary<int, string> user = new Dictionary<int, string>
            {
                {1,"Sourav" },
                {2 , "Kayal" }
            };

     7)     Use expression in single line function.

This is another nice syntactical improvement of single line function. Yes, it will return double of passed parameter.

    class myClass
    {
        public int makeDouble(int data) => data * 2;
    }

No comments:

Post a Comment