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 voidbtnTest_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 formbefore the txtResult textbox shows the result.
In the past, we can also use BeginGetResponse method to send async request as this sample in MSDNshows: 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 voidbtnTest_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 (varresponseStream = 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 themethod 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 usto 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;
namespaceConsoleApplicationTest { class Program { static void Main(string[] args) { InsertLog("Main"); MethodB(); Console.ReadLine(); }
static void MethodA(){ InsertLog("MethodA"); MethodB(); }
static void MethodB(){ }
static voidInsertLog(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 thecodes 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;
namespaceConsoleApplicationTest { 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); }
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.
Nice overview of C# lang. with Visual studio...
thks....
Nice ones, thanks
thanks for the ready info.....
Nice article. Awful formatting, though. Some block formatting of the code examples would be nice.
Nice one... Expect detail explanations in future
Thanks for info
Good Info !
good explaination with simple examples, really liked it :))
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.
Good overview - Thanks!
Rashed
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.
Good Article
Every personal site supports code formatting for user readability. Why Microsoft doesn't?
Thanks for sharing. Very useful overview.
Asyn operations in 5.0 is outstanding feature.The performance of Application should be increased;