An Introduction to New Features in C# 5.0


 

Introduction of New Features in C# 5.0

 

1. C# Evolution Matrix

Microsoft just published a new version of C# : 5.0 beta with CLR version 4.5 (Visual Studio 11 beta).
In order to get a big picture of the whole evolution of C# language, I summarized all the key features
into a C# Evolution Matrix for your reference as below diagram shows:



In C# version 5.0, there are two key features: Async Programming and Caller Information.

2. Async Feature

Two new key words are used for Async feature: async modifier and await operator. Method marked
with async modifier is called async method. This new feature will help us a lot in async programming.
For example, in the programming of Winform, the UI thread will be blocked while we use
HttpWebRequest synchronously request any resource in the Internet. From the perspective of user
experience, we cannot interact with the form before the request is done.

private void
btnTest_Click(object sender, EventArgs e)

{

var request = WebRequest.Create(txtUrl.Text.Trim());

var content=new MemoryStream();

using (var response = request.GetResponse())

{

using (var responseStream = response.GetResponseStream())

{

responseStream.CopyTo(content);

}

}

txtResult.Text = content.Length.ToString();

}


In the above example, after we clicked the Test button, we cannot not make any change to the form
before the txtResult textbox shows the result.

In the past, we can also use BeginGetResponse method to send async request as this sample in MSDN
shows:
http://msdn.microsoft.com/zh-cn/library/system.net.httpwebrequest.begingetresponse(v=vs.80).aspx. But it
will takes us a lot effort to realize it.

Now, we can simply use below code to do request asynchronously :

private async void
btnTest_Click(object sender, EventArgs e)

{

var request = WebRequest.Create(txtUrl.Text.Trim());

var content = new MemoryStream();

Task<WebResponse> responseTask = request.GetResponseAsync();

using (var response = await responseTask)

{

using (var
responseStream = response.GetResponseStream())

{

Task copyTask = responseStream.CopyToAsync(content);

//await operator to supends the excution of the method until the task is completed. In the meantime,
the control is returned the UI thread.

await copyTask;

}

}

txtResult.Text = content.Length.ToString();

}

The await operator is applied to the returned task. The await operator suspends execution of the
method until the task is completed. Meanwhile, control is returned to the caller of the suspended
method.

3. Caller Information

Caller Information can help us in tracing, debugging and creating diagnose tools. It will help us
to avoid duplicate codes which are generally invoked in many methods for same purpose, such
as logging and tracing.

We could get the below information of caller method :

Below example are a common practice prior to the new feature of Caller Information:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

namespace
ConsoleApplicationTest

{

class Program

{

static void Main(string[] args)

{

InsertLog(“Main”);

MethodB();

Console.ReadLine();

}

static void MethodA()

{

InsertLog(“MethodA”);

MethodB();

}

static void MethodB()

{ }

static void
InsertLog(string methodName)

{

Console.WriteLine(“{0} called method B at {1}”, methodName,
DateTime.Now);

}

}

}

In both Main and MethodA methods, method InsertLog is invoked for logging. Now we can change the
codes to be as per below lines:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Runtime.CompilerServices;

using System.Text;

using System.Threading.Tasks;

namespace
ConsoleApplicationTest

{

class Program

{

static void Main(string[] args)

{

//InsertLog(“Main”);

MethodB();

Console.ReadLine();

}

static void MethodA()

{

//InsertLog(“MethodA”);

MethodB();

}

static void MethodB(

[CallerMemberName] string memberName = “”,

[CallerFilePath] string sourceFilePath = “”,

[CallerLineNumber] int sourceLineNumber = 0)

{

InsertLog(memberName);

}

static void
InsertLog(string methodName)

{

Console.WriteLine(“{0} called method B at {1}”, methodName,
DateTime.Now);

}

}

}

4. Summary

The new features in C# 5.0 will help us to code more easily and improve the productivity. Have a nice
experience with the new release of Visual Studio 11!

 

Author’s Bio

Fahao Tang, Visual C# MVP, majored in Environment Engineering. In 2008, he joined
Microsoft
MSDN forums and became a moderator one year later.  Through these
forums, he helped a lot of users to resolve all kinds of questions and issues. In 2012,
he successfully joined one of the GSO hubs of the
Australia and New Zealand Banking
Group in Chengdu. The new role as Senior MIS
Developer as well as the youngest
senior developer in the department, brings
him a lot challenges with opportunities. 
Beside the improvement in work,
he also helped to organize offline technique sharing
meetings.  He is
currently a programmer and an information participator and initiator. 

MVP Mondays

The MVP Monday Series is created by Melissa Travers. In this series we work to
provide readers with a guest post from an MVP every Monday. Melissa is a
Community Program Manager for Dynamics, Excel, Office 365, Platforms and
SharePoint in the United States. She has been working with MVPs since her
early days as Microsoft Exchange Support Engineer when MVPs would answer
all the questions in the old newsgroups before she could get to them.

 

Comments (40)

  1. Patel Rikin says:

    Nice overview of C# lang. with Visual studio…

    thks….

  2. Srinivas says:

    Nice ones, thanks

  3. San says:

    thanks for the ready info…..

  4. Jim says:

    Nice article. Awful formatting, though. Some block formatting of the code examples would be nice.

  5. Diljith says:

    Nice one… Expect detail explanations in future

  6. Sat says:

    Thanks for info

  7. rajachowdary says:

    Good Info !

  8. noor says:

    good explaination with simple examples, really liked it :))

  9. jtwine says:

    When posting articles that contain code, please take the time to ensure that things like the code snippets and samples are formatted correctly.  

    Some of the information you are trying to communicate gets lost when trying to read through the code and there are places where comments are broken into multiple lines, so it looks like article content in the middle of the code sample.  

    It is also hard to see where article text ends and a code snippet/sample begins, and vice-versa.

    Thanks!

    -=- James.

  10. RKamal says:

    Good overview – Thanks!

    Rashed

  11. Dave Black says:

    Thanks for the article.  I understand the need/benefit for the 'async' and 'await' keywords, however I think your example of their usage is not the best.  You could easily accomplish an async/non-blocking operation on a WinForm using a BackgroundWorker thread.

  12. Geetha says:

    Good Article

  13. Mustafa says:

    Every personal site supports code formatting for user readability. Why Microsoft doesn't?

  14. Kiran Kurapaty says:

    Thanks for sharing. Very useful overview.

  15. Vijay Byreeddy says:

    Asyn operations in 5.0 is outstanding feature.The performance of Application should be increased;

  16. jtwine says:

    @Mustafa – the MS sites do support it.  For example, see <msdn.microsoft.com/…/hh749018>.  

    IMHO, the problem, which I believe is all too common with today's developers, is that you just have to care enough about your users and/or target audience  to actually take the time to learn how to do it *right*.  And then actually *do* it right.

    Remember: it is never to late to fix an error…

  17. Manish Taroliya says:

    Nice Article

  18. Rabish Kumar Ravi says:

    Very Nice!! Now async programming and debugging will be very very easier..

  19. Alejandro Calderon says:

    Nice explanation!

  20. Trilochan says:

    Good Overview in C# 5.0

  21. Json says:

    For the love of all things holy, please stop the proliferation of this crap:

    " var content = new MemoryStream();  "

    That's not why the var keyword was introduced.

  22. karthikMS says:

    Thanks a lot for sharing valuable information.

  23. SC Vinod says:

    Great article…very easy to understand.

  24. User Ed says:

    This blog post seems to have been made into a Wiki article here: social.technet.microsoft.com/…/12014.introduction-of-new-features-in-c-5-0-en-us.aspx

    Please let me know if the author doesn't want it to be. Thanks!

  25. Oobe says:

    @Json completely agree about the var thing.  It's just lazy.

    As for async/await.. What is the point of it?  Does the WebRequest object not already include async operations (BeginGetWebResponse and so on) or how about using a background thread?  With async/await it might look slightly prettier but is there any real advantage to the already available methods of achieving async operation?

    Seems like a reasonable idea but surely there must be more to .net 5 than this !!!

  26. taffer says:

    Missing features of the evolution matrix:

    C# 2.0: Partial classes, Iterators (yield return/break)

    C# 3.0: Partial methods, Auto properties

    C# 4.0: Generics invariance/contravariance

    Btw, caller information is not a new C# 5.0 feature. It is achieved via parameter attributes, which syntax is available since C# 1.0. So this is a feature of the new .NET framework, not the language. Otherwise, the article is ok 😉

  27. kaarthik says:

    Nice Article

  28. Jeremy says:

    The chart  from .Net 4.0 onward is a poor incentive to upgrade. The upgrade to .Net 3.0 (LINQ & Lambda's),  3.5 (WPF, WCF, WFF), .Net  4.0 (for COM and VB.Net feature equality), but the Async stuff can be achieved already and most of the usefulness of the Caller Info can be achieved with AOP. Hoping MSFT R & D will come out with a plathora of RAD projects and products for .Net 6! Despite the complaining… we're so far ahead of the java world.

  29. Raymond Tang says:

    Hi Ed Price, I am okay with it. :)

    Thank you everyone to give me the suggestions.

    @taffer, thank you very much, you are absolutely correct.

  30. immu says:

    Thanks for sharing your knowledge, nice article.

  31. Christian says:

    The blog software is poor in handling source code. Improve this, Microsoft!

  32. sathya says:

    is this visual studio 2011 r 2012?

  33. Senthil Sivanath says:

    Oh, Microsoft had VS 2011 ? I never knew that.

    Guess it should have been VS 2012.

  34. Chandra says:

    Good information..

  35. Shailendra Tiwari says:

    Thanks for sharing. Very use full information.

  36. JK says:

    That's all? Boring…

  37. mk says:

    MSDN should provide proofreaders to bloggers with poor English.

  38. Anil says:

    Async and await is working with VS2010 as well

  39. sm says:

    Thanks for info.