Click here to Skip to main content
15,888,610 members
Articles / Programming Languages / C#

Briefly exploring C# 6 new features

Rate me:
Please Sign up or sign in to vote.
4.65/5 (80 votes)
20 Aug 2014CPOL3 min read 150.5K   56   66
briefly exploring most important new features of C# 6

A few weeks ago i was reading about some of the new features coming with C# 6 in different places. I've decided to gather them so you can check them out at once if haven't already. some of them may not as amazing as expected but that the update for now.

You can get them by downloading VS 2014 or installing the Roslyn package for visual studio 2013 from here.

Update:

i add new items to the Article once they are added to Roslyn download package or remove them once they are removed from Roslyn download package.

So lets get started:

1. $ sign

 The purpose for it is to simplify string based indexing and that is all. its not some thing like current dynamic features of  C# since it internally uses regular indexing functionality. to understand lets consider following example:
C#
  var col = new Dictionary<string, string>()
            {
                // using inside the intializer
                $first = "Hassan"
            };

   //Assign value to member

   //the old way:
   col["first"] = "Hassan";
   
   // the new way   
   col.$first = "Hassan";

2. Exception filters:

Exception filters are already supported in VB compiler but now they are coming into C#. exception filters lets you specify a condition for a catch block. the catch block gets executed only if the condition is satisfied, this one is my favorite feature, so let's look at an example:
C#
try
{
    throw new Exception("Me");
}
catch (Exception ex) if (ex.Message == "You")
{
    // this one will not execute.
}
catch (Exception ex) if (ex.Message == "Me")
{
    // this one will execute
}

3. await in catch and finally block:

As far as I know, no one know why in C# 5 using await keyword in catch and finally block was not available, any way its now possible to use though. this is great because often we want to perform I/O operation in order to log the exception reason in catch block or such things in finally block and they Need asynchrony.
C#
try
{
    DoSomething();
}
catch (Exception)
{
    await LogService.LogAsync(ex);
}

4. Declaration expressions

This feature simply allows you to declare local variable in the middle of an expression. It is as simple as that but really destroys a pain. I have been doing a lot of asp.net web form projects in the past and this was my every day code:
C#
long id;
if (!long.TryParse(Request.QureyString["Id"], out id))
{ }
which can be improved to this:
C#
if (!long.TryParse(Request.QureyString["Id"], out long id))
{ }
The scoping rules for this kind of declaration is same as general scoping rules in C#.
 

5. using Static

This feature allows you to specify a particular type in a using statement after that all static members of that type will be accessible is subsequent code.
C#
using System.Console;

namespace ConsoleApplication10
{
    class Program
    {
        static void Main(string[] args)
        {
            //Use writeLine method of Console class
            //Without specifying the class name
            WriteLine("Hellow World");
        }
    }
}

6. Auto property initializer:

With C# 6 initialize auto properties just like a field at declaration place. The only thing to notice here is that this initialization dose not cause the setter function to be invoked internally. the value of backing field is set directly. so here is an example:
C#
public class Person
    {
        // You can use this feature on both
        //getter only and setter / getter only properties

        public string FirstName { get; set; } = "Hassan";
        public string LastName { get; } = "Hashemi";
    }

7. Primary Constructor:

Woohooo, primary constructors will help destroy the pain of capturing values of constructor parameters to fields in the class for further operations. This is really useful. The main purpose for it is using constructor parameters for initialization. When declaring a primary constructor all other constructors must call the primary constructor using :this().
here is an example finally:
C#
//this is the primary constructor:
class Person(string firstName, string lastName)
{
    public string FirstName { get; set; } = firstName;
    public string LastName  { get; } = lastName;
}
notice that declaration of primary constructor is at the top of the class.
 

8- Dictionary Initializer:

some people believed that the old way of initiailzing dictionaries was dirty so the C# team dicided to make it cleaner, thanks to them. here is an example of the old way and new way:

// the old way of initializing a dictionary
Dictionary<string, string> oldWay = new Dictionary<string, string>()
{
    { "Afghanistan", "Kabul" },
    { "United States", "Washington" },
    { "Some Country", "Some Capital city" }
};

// new way of initializing a dictionary
Dictionary<string, string> newWay = new Dictionary<string, string>()
{
    // Look at this!
    ["Afghanistan"] = "Kabul",
    ["Iran"] = "Tehran",
    ["India"] = "Delhi"
};

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Afghanistan Afghanistan
you can always find me at afgdeveloper.com

Comments and Discussions

 
QuestionMy vote of 5 Pin
Nick Polyak22-Aug-14 5:08
mvaNick Polyak22-Aug-14 5:08 
SuggestionMy Vote of 4 and a Suggestion Pin
Agent__00719-Aug-14 17:34
professionalAgent__00719-Aug-14 17:34 
GeneralRe: My Vote of 4 and a Suggestion Pin
Hassan Hashemi19-Aug-14 17:57
Hassan Hashemi19-Aug-14 17:57 
QuestionWhere did you get this info? Pin
William E. Kempf19-Aug-14 8:47
William E. Kempf19-Aug-14 8:47 
AnswerRe: Where did you get this info? Pin
Jeremy Todd19-Aug-14 9:17
Jeremy Todd19-Aug-14 9:17 
GeneralRe: Where did you get this info? Pin
Hassan Hashemi19-Aug-14 17:47
Hassan Hashemi19-Aug-14 17:47 
QuestionOverview is good, but features... Pin
Thornik19-Aug-14 7:17
Thornik19-Aug-14 7:17 
AnswerRe: Overview is good, but features... Pin
William E. Kempf19-Aug-14 8:36
William E. Kempf19-Aug-14 8:36 
Your criticism is overly harsh. String interpolation is being considered, but frankly, that's a feature with lots of problems that I really don't want anyway. It's not localization friendly, for instance.

1. $ sign, yeah, I find this one dumb. This article is also the first time I've heard of it, and I doubt it's in C# vNext.
2. Exception filters... this is simple syntax sugar that I could take or leave, but I guarantee you've done exception filtering in your 10 years using the more verbose syntax.
3. await in catch and finally is a very non-trivial thing to implement. Rather than holding up this much needed language feature they originally shipped without this. Now they are adding it. That's all very understandable and is the right thing to do. And if you have to say "maybe it's useful" then you don't have any real knowledge of this language feature and maybe shouldn't comment about it.
4. Declaration expressions are as much a meh as exception filters. It's funny you rant about how those are unnecessary but take the exact opposite stance here.
5. using static is actually an extremely useful feature available in several other languages. With would be useful as well, but with is usually used as a shortcut for accessing instance members, not static members. With decent initializer syntax I find it a lot less compelling to have with than using static.
6. Tons of code? There's very little extra code in assigning the value in the constructor in comparison to doing member initialization. The only reason this feature is really beneficial is for readonly properties (a fairly rare thing) and for immutable types which would be impossible to implement without primary constructors, which you find "DUMB".
7. Primary constructors have horrible syntax, IMHO, but they serve several useful purposes beyond "students for 1-line classes". They are what make your property initializer useful, vastly simplifying the code needed to write immutable types or for initializing the immutable portion of reference types that support Equals/GetHashCode. They're necessary for the pattern matching proposal not discussed here. They provide the infrastructure necessary for "required" constructors, which don't exist today (and I have seen bugs introduced that would be impossible to code if we'd had primary constructors in the past).

Pattern matching is being discussed, even if this post by someone not even working on the language doesn't mention it. We already have multiple return values in the form of both out parameters and Tuples. There's work under way to give us the last few missing pieces from Tuples to give you what you probably meant by multiple return values (i.e. tuple deconstruction). So, you're overly critical, are focused on features *you* want rather than features that are actually being asked for, and use rather harsh language. This read more as a troll than as a legitimate post.
William E. Kempf

GeneralRe: Overview is good, but features... Pin
Thornik19-Aug-14 11:43
Thornik19-Aug-14 11:43 
GeneralRe: Overview is good, but features... Pin
Hassan Hashemi19-Aug-14 17:49
Hassan Hashemi19-Aug-14 17:49 
GeneralRe: Overview is good, but features... Pin
Thornik20-Aug-14 2:54
Thornik20-Aug-14 2:54 
GeneralRe: Overview is good, but features... PinPopular
Mycroft Holmes24-Aug-14 19:55
professionalMycroft Holmes24-Aug-14 19:55 
GeneralRe: Overview is good, but features... Pin
Hassan Hashemi24-Aug-14 21:55
Hassan Hashemi24-Aug-14 21:55 
AnswerRe: Overview is good, but features... Pin
Alex_119-Aug-14 18:53
Alex_119-Aug-14 18:53 
AnswerRe: Overview is good, but features... Pin
Antonino Porcino19-Aug-14 23:27
Antonino Porcino19-Aug-14 23:27 
GeneralMy vote of 3 Pin
Er. Rahul Nagar18-Aug-14 23:53
Er. Rahul Nagar18-Aug-14 23:53 
GeneralMy vote of 5 Pin
Humayun Kabir Mamun18-Aug-14 19:12
Humayun Kabir Mamun18-Aug-14 19:12 
GeneralMy vote of 5 Pin
Renju Vinod18-Aug-14 18:28
professionalRenju Vinod18-Aug-14 18:28 
GeneralMy vote of 5 Pin
Sk. Tajbir18-Aug-14 10:40
Sk. Tajbir18-Aug-14 10:40 
QuestionMissing actual new code in example of using Static Pin
Matt T Heffron18-Aug-14 8:21
professionalMatt T Heffron18-Aug-14 8:21 
AnswerRe: Missing actual new code in example of using Static Pin
PIEBALDconsult18-Aug-14 8:37
mvePIEBALDconsult18-Aug-14 8:37 
GeneralRe: Missing actual new code in example of using Static Pin
Matt T Heffron18-Aug-14 9:57
professionalMatt T Heffron18-Aug-14 9:57 
GeneralRe: Missing actual new code in example of using Static Pin
PIEBALDconsult18-Aug-14 10:00
mvePIEBALDconsult18-Aug-14 10:00 
GeneralRe: Missing actual new code in example of using Static Pin
Hassan Hashemi18-Aug-14 18:21
Hassan Hashemi18-Aug-14 18:21 
GeneralRe: Missing actual new code in example of using Static Pin
PIEBALDconsult19-Aug-14 4:41
mvePIEBALDconsult19-Aug-14 4:41 

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.