User Name:


User Email:




This information will only be saved for the purposes of communicating with those who have provided this information voluntarily regarding our services.We will never sell your name or email address to anyone.
© 2017 - First Crazy Developer (Abhishek Kumar)
  

crazydeveloper New cool features in C# 6.0

Hi friend, last week I installed new Visual Studio 2015 and I went through some cool features. Then after I thought we should discuss about that features of C# 6. In this article we will overview these new concepts then after we will discuss in details. We know Microsoft released Visual Studio 2015 with C# 6.

In this version, we can see that a lot of syntax changes have occurred since its inception. Because of this, I’ve noticed that most of the blog posts currently on the internet don’t work anymore or are too vague about how they implemented a feature.

I thought it would be useful to make a list of the most essential C# 6 features with simple code examples with comparison with previous version would make it both easy to understand and simple to copy/paste a sample into a new console app to try it. Let’s start.

Static Using Syntax

In previous versions of C#, if we wanted to print something to the Console, look at the following line of code:

  1. using System;
  2. namespace CSharpSix
  3. {
  4. class Program
  5. {
  6. static void Main(string[] args)
  7. {
  8. Console.WriteLine("Hello First Crazy Developer!!!");
  9. }
  10. }
  11. }


In the C# 6, we can now add the using static qualifier and reference the WriteLine method by itself as shown below:

Look at the following Code:

  1. using static System.Console;
  2. namespace CSharpSix
  3. {
  4. class Program
  5. {
  6. static void Main(string[] args)
  7. {
  8. WriteLine("Hello First Crazy Developer!!!");
  9. }
  10. }
  11. }


This also works for classes that we’ve created user defined static class. Look at the following example:

  1. using static System.Console;
  2. using static CSharpSix.SampleStatic;
  3. namespace CSharpSix
  4. {
  5. class Program
  6. {
  7. static void Main(string[] args)
  8. {
  9. WriteLine("Hello World!");
  10. CallCoolFeature ();
  11. }
  12. }
  13. static class SampleStatic
  14. {
  15. public static void CallCoolFeature ()
  16. {
  17. WriteLine("Hello First Crazy Developer!!!");
  18. }
  19. }
  20. }

In the above code we can see SampleStatic class with the static keyword, we can execute the method by just calling the method name. The output for this sample would be:

Hello World!
Hello First Crazy Developer!!!

Auto-Property Initializers

In the past, we may have created our properties with a getter and setter and initialized our Constructor with the value as shown below.

Look at the following code:

  1. using System;
  2. namespace CSharpSix
  3. {
  4. class Program
  5. {
  6. static void Main(string[] args)
  7. {
  8. AutoPropertyInitializers sData = new AutoPropertyInitializers ();
  9. Console.WriteLine(sData.myID);
  10. Console.ReadLine();
  11. }
  12. }
  13. public class AutoPropertyInitializers
  14. {
  15. public AutoPropertyInitializers ()
  16. {
  17. myID = Guid.NewGuid();
  18. }
  19. public Guid myID { get; set; }
  20. }
  21. }

Againg we get cool feature in C# 6. Here we can modify the AutoPropertyInitializers class and populate the property called myID with inline initialization Cool...!!!

Look at the following code:

  1. using System;
  2. using static System.Console;
  3. namespace CSharpSix
  4. {
  5. class Program
  6. {
  7. static void Main(string[] args)
  8. {
  9. AutoPropertyInitializers autoProperty = new AutoPropertyInitializers();
  10. WriteLine(autoProperty.myID); ReadLine();
  11. }
  12. }
  13. public class AutoPropertyInitializers
  14. {
  15. public Guid myID { get; set; } = Guid.NewGuid();
  16. }
  17. }

The output of the above code will be a random guid generated by the system.

Dictionary Initializers

In C# 5, we would initialize the Dictionary with a {"Key", "Value"} syntax, as in the example below.

Look at the following code:

  1. using System.Collections.Generic;
  2. namespace CSharpSix
  3. {
  4. class Program
  5. {
  6. static void Main(string[] args)
  7. {
  8. var sampleData= new Dictionary<string, string> ()
  9. {
  10. { "Michael Jordon", "Basketball" },
  11. { "Peyton Manning", "Football" },
  12. { "Babe Ruth", "Baseball" }
  13. };
  14. foreach (KeyValuePair<string, string> keyValuePair in stars)
  15. {
  16. Console.WriteLine(keyValuePair.Key + ": " +
  17. keyValuePair.Value + "\n");
  18. }
  19. Console.ReadLine();
  20. }
  21. }
  22. }

In C# 6, we just place the key between two square brackets ["Key"] and then set the value of the key ["Key"] = "value". This syntax is cleaner, in my opinion, and reduces the amount of errors that the old way produced.

Look at the folowing code:

  1. using System.Collections.Generic;
  2. using static System.Console;
  3. namespace CSharpSix
  4. {
  5. class Program
  6. {
  7. static void Main(string[] args)
  8. {
  9. var sampleData = new Dictionary<string, string>()
  10. {
  11. ["First Crazy Developer"] = "My Blog",
  12. ["Coding Almanac"] = "Developer Wall",
  13. ["Full Stack Developer"] = "Abhishek Kumar"
  14. };
  15. foreach (KeyValuePair<string, string> keyValuePair in sampleData)
  16. {
  17. WriteLine(keyValuePair.Key + ": " +
  18. keyValuePair.Value + "\n");
  19. }
  20. ReadLine(); }
  21. }
  22. }

String Interpolation


In previous version, we typically concatenated two or more strings together with one of the following methods:

Look at the following code:

  1. using System;
  2. namespace CSharpSix
  3. {
  4. class Program
  5. {
  6. static void Main(string[] args)
  7. {
  8. string firstName = "Michael";
  9. string lastName = "Crump";
  10. Console.WriteLine("Name : " + firstName + " " + lastName);
  11. Console.WriteLine("Name : {0} {1}", firstName, lastName);
  12. Console.ReadLine();
  13. }
  14. }
  15. }

But in C# 6.0, we have a cleaner way to format a string by writing our own arguments instead of referring to them as placeholders. Just make sure we use the $ before the start of the string.

Look at the following code:

  1. using static System.Console;
  2. namespace CSharpSix
  3. {
  4. class Program
  5. {
  6. static void Main(string[] args)
  7. {
  8. string firstName = "Abhishek";
  9. string lastName = "Kumar";
  10. WriteLine($"{firstName} {lastName} is my name!");
  11. ReadLine(); }
  12. }
  13. }

If we executed the above code get output for this example is:

Abhishek Kumar is my name!

nameOf Expression

This feature was designed due to the large amounts of code that many enterprise level applications have. One common error is using hard-coded name strings with an error message. Due to the nature of the apps in general and re-factoring, sometimes the names change and the string representation is left alone – thus breaking the app. Here is an example.

Look at the following code:

  1. using System;
  2. using static System.Console;
  3. namespace CSharpSix
  4. {
  5. class Program
  6. {
  7. static void Main(string[] args)
  8. {
  9. SampleMethod ("First Crazy Developer ");
  10. ReadLine();
  11. }
  12. public static void SampleMethod (string oldParameter)
  13. {
  14. if (oldParameter == null) throw new Exception("oldParameter is null");
  15. }
  16. }
  17. }

When we execute the above code will not produce an error as expected as the string is equal to null.

What happens if someone changes the name variable to oldParameter? Since us hard-coded the “Name is null” error that is what will appear to the end-user. We would rather it now say, “oldParameter is null”, but the compiler cannot recognize this mistake.

In C# 6.0, we can refactor our code to remove the string literals and use the nameof expression.

Look at the following code:

  1. using System;
  2. using static System.Console;
  3. namespace CSharpSix
  4. {
  5. class Program
  6. {
  7. static void Main(string[] args)
  8. {
  9. SampleMethod("First Crazy Developer");
  10. ReadLine();
  11. }
  12. public static void SampleMethod(string newParameter)
  13. {
  14. if (newParameter == null) throw new Exception(nameof(newParameter) + " is null");
  15. } }
  16. }

We can say now above code is cleaner code and type safety when retrieving member names. In this case, if we removed the newParameter variable and gave it a new name then the compiler would catch the error before the program was executed.

Expression Bodied Function & Property

Functions and properties in lambda expressions save you from defining your function and property statement block.

Look at the following code:

  1. using static System.Console;
  2. namespace CSharpSix
  3. {
  4. class Program
  5. {
  6. private static double MultiplyNumbers(double num1, double num2) => num1 * num2;
  7. static void Main(string[] args)
  8. {
  9. double num1 = 5;
  10. double num2 = 10;
  11. WriteLine(MultiplyNumbers(num1, num2));
  12. ReadLine();
  13. }
  14. }
  15. }

When we execute the above code output would be 50.

This shorthand notation may be confusing at first, but I think after you get used to it then can make your program much more readable.

Exception Filters

Exception filters have been supported in Visual Basic, but are new to the C# compiler. They allow you to specify a condition for a catch block. We typically used the following in C# 5:

Look at the following code:

  1. using System;
  2. using static System.Console;
  3. namespace CSharpSix
  4. {
  5. class Program
  6. {
  7. static void Main(string[] args)
  8. {
  9. var httpStatusCode = 404;
  10. Write("HTTP Error: ");
  11. try
  12. {
  13. throw new Exception(httpStatusCode.ToString());
  14. }
  15. catch (Exception ex)
  16. {
  17. if (ex.Message.Equals("500"))
  18. Write("Bad Request");
  19. else if (ex.Message.Equals("401"))
  20. Write("Unauthorized");
  21. else if (ex.Message.Equals("402"))
  22. Write("Payment Required");
  23. else if (ex.Message.Equals("403"))
  24. Write("Forbidden");
  25. else if (ex.Message.Equals("404"))
  26. Write("Not Found");
  27. }
  28. ReadLine();
  29. }
  30. }
  31. }

Rather than entering the catch block and checking to see which condition met our exception, we can now decide if we even want to enter the specific catch block.

Look at the following code:

  1. using System;
  2. using static System.Console;
  3. namespace CSharpSix
  4. {
  5. class Program
  6. {
  7. static void Main(string[] args)
  8. {
  9. var httpStatusCode = 404;
  10. Write("HTTP Error: ");
  11. try
  12. {
  13. throw new Exception(httpStatusCode.ToString());
  14. }
  15. catch (Exception ex) when (ex.Message.Equals("400"))
  16. {
  17. Write("Bad Request");
  18. ReadLine();
  19. }
  20. catch (Exception ex) when (ex.Message.Equals("401"))
  21. {
  22. Write("Unauthorized");
  23. ReadLine();
  24. }
  25. catch (Exception ex) when (ex.Message.Equals("402"))
  26. {
  27. Write("Payment Required");
  28. ReadLine();
  29. }
  30. catch (Exception ex) when (ex.Message.Equals("403"))
  31. {
  32. Write("Forbidden");
  33. ReadLine();
  34. }
  35. catch (Exception ex) when (ex.Message.Equals("404"))
  36. {
  37. Write("Not Found");
  38. ReadLine();
  39. }
  40. ReadLine();
  41. }
  42. }
  43. }

Await in a Catch and Finally Block

Again we have awesome feature with C# 6, you can write asynchronous code inside in a catch/finally block. This will help developers as they often need to log exceptions to a file or database without blocking the current thread. Here is an example of how this work:

Look at the following code:

  1. using System;
  2. using System.Net.Http;
  3. using System.Threading.Tasks;
  4. using static System.Console;
  5. namespace CSharpSix
  6. {
  7. class Program
  8. {
  9. static void Main(string[] args)
  10. {
  11. Task.Factory.StartNew(() => GetWebSiteContent ());
  12. ReadLine();
  13. }
  14. private async static Task GetWebSiteContent()
  15. {
  16. HttpClient client = new HttpClient();
  17. try
  18. {
  19. var result = await client.GetStringAsync("http://www.firstcrazydeveloper.com");
  20. WriteLine(result);
  21. }
  22. catch (Exception exception)
  23. {
  24. try
  25. {
  26. //This asynchronous request will run if the first request failed.
  27. var result = await client.GetStringAsync("http://www.codingalmanac.com");
  28. WriteLine(result);
  29. }
  30. catch
  31. {
  32. WriteLine("Entered Catch Block");
  33. }
  34. finally
  35. {
  36. WriteLine("Entered Finally Block");
  37. }
  38. }
  39. }
  40. }
  41. }

Null Conditional Operator

Every developer hates NullReferenceException errors! This is the typical code one would check prior to C# 6.0.

Look at the following code:

  1. using System;
  2. using static System.Console;
  3. namespace CSharpSix
  4. {
  5. class Program
  6. {
  7. static void Main(string[] args)
  8. {
  9. SampleData sData = new SampleData();
  10. if (sData.MyName == String.Empty)
  11. {
  12. sData = null;
  13. }
  14. WriteLine(sData != null ? sData.MyName : "Field is null.");
  15. ReadLine();
  16. ReadLine();
  17. }
  18. }
  19. public class SampleData
  20. {
  21. public string MyName { get; set; } = "";
  22. }
  23. }

When we execute the above code returns “Field is null”. If we enter some data into name, then the console prints out whatever is contained in the name.

We have new feture in C# 6.0 to handle this, we can use?. to check if an instance is null or not. The code listing below will print the sData.MyName field if one is supplied or will print “Field is null” if one isn’t supplied.

Look at the following code:

  1. using System;
  2. using static System.Console;
  3. namespace CSharpSix
  4. {
  5. class Program
  6. {
  7. static void Main(string[] args)
  8. {
  9. Person person = new Person();
  10. if (person.Name == String.Empty)
  11. {
  12. person = null;
  13. }
  14. WriteLine(person?.Name ?? "Field is null.");
  15. ReadLine();
  16. }
  17. }
  18. public class Person
  19. {
  20. public string Name { get; set; } = "";
  21. }
  22. }

Thankfully C# 6.0 is final and can be used in production environments now. I wasn’t able to touch on every feature, but you can always reference MSDN for more info.

I would also encourage you to check out what is included in Visual Studio 2015 while you are there. With Visual Studio 2015 we can use some of the cool new C# 6 features that we discussed in this article.

So did we miss a cool feature or do you have a better way to do something? Sounds off in the comments below!

Full source code of New Cool Features of C# 6.0

Happy reading!!!
Abhishek Kumar




crazydeveloper Home Page 17 October 2015

Become a Fan