Click here to Skip to main content
15,881,172 members
Articles / Programming Languages / C#
Tip/Trick

C# 6.0 New Features Explored

Rate me:
Please Sign up or sign in to vote.
4.54/5 (14 votes)
26 Dec 2014CPOL4 min read 25K   10   4
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:
C#
  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.
C#
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();
        }
Image 1

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.

Image 2

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.

C#
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.

C#
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:

C#
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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



Comments and Discussions

 
GeneralMy vote of 1 Pin
DanBran194929-Dec-14 11:16
professionalDanBran194929-Dec-14 11:16 
GeneralRe: My vote of 1 Pin
Srinivasa Dinesh Parupalli29-Dec-14 17:49
professionalSrinivasa Dinesh Parupalli29-Dec-14 17:49 
Questionsoruse bazi doz Pin
Member 1133746726-Dec-14 21:59
Member 1133746726-Dec-14 21:59 
لطفا برنامه ی بازی دوز برام بفرستید
AnswerRe: soruse bazi doz Pin
W. Kleinschmit29-Dec-14 0:17
W. Kleinschmit29-Dec-14 0:17 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.