Thursday 31 October 2013

New features added in C# 5.0

C# most recent version 5.0 was released on August 15, 2012 with .NET Framework 4.5 and Visual Studio 2012.

There are two main features in C# 5.0 - Async Programming and Caller Information. Let's understand both these features in details as given below.

Async Feature (Asynchronous Methods)

C# 5.0 Async feature introduces two keywords async and await which allows you to write asynchronous code more easily and intuitively like as synchronous code. Before C# 5.0, for writing an asynchronous code, you need to define callbacks (also known as continuations) to capture what happens after an asynchronous process finishes. This makes your code and other routine task such exception handling complicated.

Both the keywords are used in a combination of each other. Hence, an await operator is applied to a one or more than one expressions of an async method. An async method returns a Task or Task<TResult> that represents the ongoing work of the method. The task contains information that the caller of the asynchronous method can use, such as the status of the task, its unique ID, and the method's result.

  1. public async Task<IEnumerable<Product>> GetProductList()

  2. {

  3. HttpClient client = new HttpClient();

  4. Uri address = new Uri("http://dotnet-tricks.com/");

  5. client.BaseAddress = address;

  6.  
  7. HttpResponseMessage response = await client.GetAsync("myservice/product/ProductList");

  8.  
  9. if (response.IsSuccessStatusCode)

  10. {

  11. var list = await response.Content.ReadAsAsync<IEnumerable<Product>>();

  12. return list;

  13. }

  14. else

  15. {

  16. return null;

  17. }

  18. }


Caller Information (Caller info attributes)


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

You could get the following information of caller method:



  1. CallerFilePathAttribute


    Full path of the source file that contains the caller. This is the file path at compile time.



  2. CallerLineNumberAttribute


    Line number in the source file at which the method is called.



  3. CallerMemberNameAttribute


    Method or property name of the caller.

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6.  
  7. class Example
  8. {
  9. static void Main(string[] args)
  10. {
  11. Console.WriteLine("Main method Start");
  12. InsertLog("Main");
  13. MyMethodB();
  14. MyMethodA();
  15. Console.WriteLine("Main method End!");
  16. Console.ReadLine(); // hold on result
  17. }
  18.  
  19. static void MyMethodA()
  20. {
  21. InsertLog("MyMethodA");
  22. MyMethodB();
  23. }
  24.  
  25. static void MyMethodB()
  26. {
  27. // some code here.
  28. }
  29.  
  30. static void InsertLog(string method)
  31. {
  32. Console.WriteLine("{0} called MyMethodB at {1}", method,
  33. DateTime.Now);
  34. }
  35. }
  36. /* Output:
  37. Main method Start
  38. Main called MyMethodB at 11/17/2013 11:12:24 PM
  39. MyMethodA called MyMethodB at 11/17/2013 11:12:24 PM
  40. Main method End!
  41. */

In both Main and MyMethodA, method InsertLog is invoked for logging. Now we can change the above code as follows.

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Runtime.CompilerServices;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6.  
  7. class Example
  8. {
  9. static void Main(string[] args)
  10. {
  11. Console.WriteLine("Main method Start");
  12. MyMethodB();
  13. MyMethodA();
  14. Console.WriteLine("Main method End!");
  15. Console.ReadLine();
  16. }
  17.  
  18. static void MyMethodA()
  19. {
  20. MyMethodB();
  21. }
  22.  
  23. static void MyMethodB([CallerMemberName] string memberName = "", [CallerFilePath] string sourceFilePath = "", [CallerLineNumber] int sourceLineNumber = 0)
  24. {
  25. InsertLog(memberName);
  26. }
  27.  
  28. static void InsertLog(string method)
  29. {
  30. Console.WriteLine("{0} called MyMethodB at {1}", method, DateTime.Now);
  31. }
  32. }
  33.  
  34. /*Output:
  35. Main method Start
  36. Main called MyMethodB at 11/17/2013 10:30:11 PM
  37. MyMethodA called MyMethodB at 11/17/2013 10:30:11 PM
  38. Main method End!
  39. */


Hope you like these new features of C# 5.0.