Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

C# 6.0 New Features Explored

0.00/5 (No votes)
26 Dec 2014 1  
This tip consists of my exploration of the C# 6.0 new features.

Introduction

I was exploring VS 2015 features and thought that why not I write new features which have been added to C# 6.0. And then, I just started exploring C# feature in 6.0 version and thought a while that C# has come a long and great way. It was approximately 12 years ago that the very first version of C# got released. From then, there have been very cool and interesting features which got added into each version of C#.

C# version Main features
1.0 (2001/2002) This was the basic version and came with new .NET framework.
2.0 (2005) Generics etc. which made the developers to think about programming in more generic ways.
3.0 (2007) Lamdas, LINQ, etc. which were great features where developers were able to SQL type queries in the C#.
4.0 (2010) Dynamics etc. which was a really cool feature in this version.
5.0 (2012) Task, Async, await etc. parallel task or asynchronous programming made easier and more flexible to developers.
6.0 (2013/2014) Property Initializer, Primary Constructors etc. which are not that great features but they add more flexibility to developers in C# 6.0. Note: In this version, C# team has put more work on the behind the scenes improvement on C# compiler. The name of the compiler is”Roslyn”. From this version, C# complier comes as a Complier as a Service, which is great news where we can have our own product like VS IDE.

I would like to describe these features by using examples (wherever applicable) which I believe that examples give more clarity than pages and pages of theory. So let’s start with new features of C# 6.0.

Note 1: The examples which are given in this tip are just to give information on the new features which were added, you can explore more on MSDN and implement in your project in a realistic way. And also, I tried to give examples wherever it is necessary. Note 2: I have used VS 2015 preview version for this article.

1. Automatic Property Initializer

Let's say, we have a class AutoInitializerProperties_Person and I have properties like below:
  public class AutoInitializerProperties_Person
    {
        public string Salutation { get; } = "Mr.";
        public string FirstName { get; } = "Srinivasa Dinesh";
        public string LastName { get; } = "Parupalli";
}

Now we can see from the above that we do not have a setter (set keyword in the declaration) in the properties. At runtime, the value which has been initialized would be considered. We need not have a constructor to assign these values. I like this feature as in the unit tests I need to have a test initialization and I can directly use the class and its initialized values. One more thing which I like is these are very useful when we do data transfers using Data Transfer Objects.

Let’s call this class in the console application.
static void Main(string[] args)
        {
            AutoInitializerProperties_Person testPerson = new AutoInitializerProperties_Person();
            StringBuilder sbPerson = new StringBuilder();
            sbPerson.Append("Hello!, ") .Append(testPerson.Salutation) .Append(" ")
                .Append(testPerson.FirstName) .Append(" ") .Append(testPerson.LastName);
            Console.WriteLine(sbPerson.ToString());
            Console.ReadKey();
        }

2. Static Using Statement

The new cool way of using the USING statement, which I think is the refined way of using it. Static USING should be on a static type which is nothing but just a static reference which can be used. Let’s have an example around it.

So from the above example, you can see the new way of defining and using the new static class usage which is invoking the methods without mentioning the static type name. The limitation though is that no two types should have the same names. And also, if instance name in an instance type has the same name of static type, then invoking of instance type wins.

3. New Way of Object Creation called Primary Constructor

4. Event Initializers

5. Index Initializers for Dictionary Collections

Now the dictionaries can be initialized by having index initializers. Let's have an example around it. For this example, I have modified the AutoInitializerProperties_Person class.

Dictionary<string, AutoInitializerProperties_Person> userOfthisSystem =
           new Dictionary<string, AutoInitializerProperties_Person>()
           {
               ["SuperAdminstrator"] = new AutoInitializerProperties_Person("CEO", "Srini", "Dinesh"),
               ["Adminstrator"] = new AutoInitializerProperties_Person("IT", "Shanker", "Pemberti"),
               ["NormalUser"] = new AutoInitializerProperties_Person("User", "Test", "Test"),
           }; 

The above new way of dictionary creation and initialization is more readable than that was currently present. And as per the MSDN documentation, this is one of the new ways of CLR improvement. If you see the CLR code, you would see the difference between the old way and new way of dictionary creation. I would like you to try the old way and verify with CLR code and then with the new way and verify with the CLR code.

6. Using of IEnumerables Arrays in the Params of a Parameter in the Method

The advantage of using IEnumerables instead of arrays is more towards lazy sequence initialization.

7. Now we can use await keyword in the catch and finally block

This is more useful in a transactions or logging things in asynchronously.

8. Another cool feature which I like is the exception filtering

This feature also, I consider to be an refinement from the older version. In the older versions of C#, if we need to not want to propagate the exception we used to have like below sample.

catch(Exception ex)
            {
                if (ex.InnerException != null)
                {
                    throw;
                }
            }

But now it is more simplified. The conditional expression should return true or false so that exception can be propagated or not. You can even have the method blocks which return true or false (i.e.) Boolean value. This is like below:

catch (Exception ex) if(ex.InnerException != null)
            {
                throw;
            }

I know there are few more new and cool features added to this new version of C#. As I said, I am still exploring them and I would definitely try to incorporate few more features by updating this post.

I can say that this new version of C# made me write fewer lines of code and explicit code.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here