C# 5.0 New Features and Asynchronous Programming

 Contents

What’s New in C# 5.0?

Simultaneous Execution Using Asynchronous Programming

Climb up the Call Stack with Caller Information

Can You Solve This Coding Problem?

Other Bits

What’s New in C#?

Welcome to the latest news from TalkIT. This month we are going to consider the C# 5.0 new features. We introduced the new features of C# 3.0 and 4.0 in the December 2013 newsletter. We now have C# 6.0, but we’ll regress to tour C# 5.0’s new features, since a lot of our readers are still working with this.New TalkIT publish a full e-learning course in C#.

These are just my ideas, based on 12 years experience training and developing. Just add your comments at the bottom of the blog.

It is interesting how the language has grown over the last decade. The initial vision for the language was to keep the number of C# keywords small, but with each new addition keywords have been added. Its creator Anders Hejlsberg intended it to be a simple, modern, general-purpose, object-oriented programming language. New features are added, with each version of the .Net framework. These allow C# to keep pace with other popular languages like C++ and Java. They also aim to make the syntax even more concise.

C# 5.0 comes with the .Net Framework 4.5 in Visual Studio 2012 and 13.

Here is an evolution matrix.

C#

The next version of the C# compiler (“Roslyn”) is open source. There are also significant language improvements within C# 6.0.C# 6.0 you may want to consider its features and explore those that might be helpful. Here is a list.

  • Indexed Members and Element Initializers
  • Auto-Properties with Initializers
  • Primary Constructors
  • Static Using Statements
  • Declaration Expressions
  • Additional Numeric Literal Formats
  • Null-Conditional Operator
  • Auto-Property Initializers
  • Nameof Expressions
  • Primary Constructors

Find out more from:

https://msdn.microsoft.com/en-us/magazine/dn683793.aspx

Simultaneous Execution Using Asynchronous Programming

Asynchronous programming, of course, means running two bits of code asynchronously or at the same time. Computers have long being equipped with multi tasking and more recently multi processors. But coding asynchronously operations has presented problems. Over the years .Net has provided several additional features that claim to simplify this. These include:

  • The framework Threading classes
  • Asynchronous C# delegates
  • The Background Worker component
  • Asynchronous methods provided with some framework classes

For more on asynchronously operations have a go at the TalkIT C# parallelization tutorial:

http://talk-it.biz/tutorial-links/16-multithreading-parallelization/

C# 5.0 new features also includes two new keywords its asynchronous feature. These are the async modifier and the await operator. A method marked with async modifier is called an async method. This feature makes asynchronously programming more straightforward as shown in this example.

This example uses a Windows Form that makes a web request. Typically with a Windows Form, the UI thread will be blocked while a web resource is accessed. This means the user cannot interact with the form until the request is complete.Form

Here is how we avoid this situation. The form remains responsive to the user. The application accepts a URL, then makes a web request for this and displays the length of the returned page.

private async void btnTest_Click_1(object sender, EventArgs e)
{
MessageBox.Show("test");
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();

}

Climb up the Call Stack with Caller Information

Caller Information can help with tracing, debugging and creating diagnostic tools. When we want to fix a bug in a method, it helps to know about the method that called our broken method. This information is always available from the .Net Call Stack. This contains details of all the methods that have previously been executed.

So we may want to know this information about our caller method :

This information can then be used for debugging the error. Or we may just want to log it somewhere. Caller Information can avoid duplicate code used for logging and tracing. To get Caller Information to work C# attributes are used on MethodB’s parameters.

In this demo Main calls MethodA, then MethodA calls MethodB. Finally MethodB calls InsertLog, which displays the caller’s name.

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);
}
}console


 

Can you solve this coding problem?

Let’s look at sorting. The aim is to write a short and elegant program to sort numbers. Use any programming language.Numbers

  1. Input some numbers
  2. Sort them
  3. Display the results.

Sorting is a fundamental algorithm and a common function. But how do we do it? We could use the bubble sort or the tree sort algorithm.

A bubble sort repeatedly steps through the list to be sorted, compares each pair of adjacent items and swaps them if they are in the wrong order.

http://en.wikipedia.org/wiki/Bubble_sort

You can then enhance your code to sort words or offer the option of an ascending or descending sort.

Other Bits

TalkIT has been very active on social media recently. We have been posting on coding, new gadgets and IT humour. Why don’t you connect with us on Twitter or FaceBook. You can follow all the latest news and let us know what you think.bits

Twitter  @NowTalkIT               FaceBook  NowTalkIT

Here are some recent tweets.

  • Java course for OO developers. Cover programming constructs and API’s quickly. #talkIT #Java #elearning http://ow.ly/HRV7U  #coding
  • How to use Response.Redirect? Find out on #TalkIT http://ow.ly/IndBJ  #Csharp #elearning #coding #mvc
  • How much time you spend debugging your code? 4 coding tutorials http://talk-it.biz/  #javascript #html5 #java #C
  • Accomplish security in ASP. NET application using inbuilt security features. #Csharp #talkIT #coding #elearning http://ow.ly/Inbqw 

New online courses in C++ and Python will be added to the TalkIT site in the next few months. Take an advanced look at what is in the courses:

C++ in late February

http://talk-it.biz/course/c-programming-training/

Python in April

http://talk-it.biz/course/python-programming/

In December we published a full Java courses. There is a launch offer of £4.99 per course monthly or £9.99 for Gold monthly subscription till end February.

Thanks to Fahao Tang MVP for his code samples

Photos www.freedigitalphotos.net/

David Ringsell MCPD 2015 ©

 

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top