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:
https://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 :
- CallerFilePathAttribute Full path of the source
file that contains the caller. This is the file path at compile time. - CallerLineNumberAttribute Line number in the
source file at which the method is called. - CallerMemberNameAttribute Method or property
name of the caller.
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
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
Anonymous
April 01, 2012
Nice overview of C# lang. with Visual studio... thks....Anonymous
April 05, 2012
Nice ones, thanksAnonymous
April 05, 2012
thanks for the ready info.....Anonymous
April 05, 2012
Nice article. Awful formatting, though. Some block formatting of the code examples would be nice.Anonymous
April 08, 2012
Nice one... Expect detail explanations in futureAnonymous
April 09, 2012
Thanks for infoAnonymous
April 09, 2012
Good Info !Anonymous
April 12, 2012
good explaination with simple examples, really liked it :))Anonymous
April 14, 2012
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.Anonymous
April 17, 2012
Good overview - Thanks! RashedAnonymous
April 17, 2012
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.Anonymous
April 18, 2012
Good ArticleAnonymous
April 19, 2012
Every personal site supports code formatting for user readability. Why Microsoft doesn't?Anonymous
April 24, 2012
Thanks for sharing. Very useful overview.Anonymous
April 30, 2012
Asyn operations in 5.0 is outstanding feature.The performance of Application should be increased;Anonymous
May 01, 2012
@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...Anonymous
May 04, 2012
Nice ArticleAnonymous
May 07, 2012
Very Nice!! Now async programming and debugging will be very very easier..Anonymous
May 09, 2012
Nice explanation!Anonymous
May 13, 2012
Good Overview in C# 5.0Anonymous
May 30, 2012
The comment has been removedAnonymous
July 18, 2012
Thanks a lot for sharing valuable information.Anonymous
August 18, 2012
Great article...very easy to understand.Anonymous
August 28, 2012
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!Anonymous
September 03, 2012
@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 !!!Anonymous
September 28, 2012
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 ;)Anonymous
December 02, 2012
Nice ArticleAnonymous
December 08, 2012
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.Anonymous
December 27, 2012
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.Anonymous
January 29, 2013
Thanks for sharing your knowledge, nice article.Anonymous
February 07, 2013
The blog software is poor in handling source code. Improve this, Microsoft!Anonymous
February 14, 2013
is this visual studio 2011 r 2012?Anonymous
March 31, 2013
Oh, Microsoft had VS 2011 ? I never knew that. Guess it should have been VS 2012.Anonymous
September 09, 2013
excellent artical.......Anonymous
November 12, 2013
Good information..Anonymous
January 22, 2014
Thanks for sharing. Very use full information.Anonymous
April 01, 2014
That's all? Boring...Anonymous
April 08, 2014
MSDN should provide proofreaders to bloggers with poor English.Anonymous
September 28, 2014
Async and await is working with VS2010 as wellAnonymous
February 03, 2016
Thanks for info.