To demonstrate the new features in C# 6.0 I have chosen small examples which will help you to understand the C# 6.0 new features easily.
I have tried to make it as simple as I can, with small examples which can be enhanced with complex scenarios as per your requirement.
List of new features in C# 6.0
- Manipulating string using string interpolation
- Using null conditional operator
- Using Await in catch and finally block
- Adding Exception Filter
- Auto properties initializer
- Using getter only auto properties
- Converting to expression-bodied function member
- Using Static
Let’s start looking at each feature before C# 6.0 and after this version. Here I am going to explain it one by one with examples.
Manipulating string using string interpolation
It can be looked at as an improvement to the String.Format functionality where, instead of the place holders, you can directly mention the string expressions or variables.
- Place strings where we need them
- Specify a space after/before the string
- Use conditions
- class Program
- {
- public string FirstName { get; set; }
- public string LastName { get; set; }
-
- public string GetFullName(string firstName, string lastName) => firstName + lastName;
- static async void Main(string[] args)
- {
-
- string firstName = "Jignesh";
- string lastName = "Kumar";
- Console.WriteLine("Full Name of Employee {0} {1}", firstName, lastName);
-
-
-
- Console.WriteLine($"Full Name of Employee {firstName} {lastName}");
-
- Console.ReadLine();
- }
- }
Using null conditional operator
Most of the time developers get this exception: “object reference not set to an instance of an object”. In C# 6 we can handle this easily using NULL Conditional Operator. So we can handle System.NullReferenceException using this operator. Please have a look at the below code andyou will easily understand how it will save time.
- class Program
- {
-
- static async void Main(string[] args)
- {
- #region Simple Condition
-
- var employees = new List<EmployeeDetail>();
-
- var address = employees != null ? employees[0].address : null;
-
-
-
- var addressNew = employees[0]?.address ?? null;
- #endregion
-
- #region Nested Condition
-
-
- if (employees != null && employees[0] != null)
- {
- var city = employees[0].address.city;
- }
- var empCity = employees != null ? (employees[0].address != null ? employees[0].address.city : null) : null;
-
-
- var employeeCity = employees[0]?.address?.city;
- #endregion
-
- }
- }
Using Await in catch and finally block
Prior to C# 6.0, it was not possible to call async operations in catch {} and finally {} blocks by specifying the await keyword due to implementation specific issues in the C# compiler. Now you will be able to call the await statements in catch {} and finally {} blocks without writing any complicated code. The compiler will automatically handle it.
Here is a code snippet to show you how easily you can call the await for async operations in catch {} and finally {} blocks. Most of the time, we need this to log exceptions and/or do some final clean-ups of the resources
- class Program
- {
-
- static async void Main(string[] args)
- {
- Exception exception = null;
- try
- {
- throw new Exception("Something went wrong");
- }
- catch (Exception ex)
- {
- exception = ex;
- }
- if (exception != null)
- {
- await LogDataAsync("Oops error occuered => ", exception);
- }
-
-
- try
- {
- throw new Exception("Something went wrong");
- }
- catch (Exception ex)
- {
- await LogDataAsync("Oops error occuered => ", ex);
- }
- finally
- {
- await LogDataAsync("Exception Logging Completed.", null);
- }
- }
- public static async Task LogDataAsync(string message, Exception exception)
- {
- using (var file = File.AppendText("issue.log"))
- {
- await file.WriteLineAsync($"{message} {exception?.ToString()}");
- }
- }
- }
Adding Exception Filter
Well, in previous versions of C# what we'd need to do is actually write an if clause that checks that property. And in this case it will be a message, and we would check to see whatever value we cared about, and then take the action that we needed. But in C# 6.0, the syntax for these situations has been simplified by using the when keyword in an exception filter.
- class Program
- {
- static async void Main(string[] args)
- {
- try
- {
- throw new Exception("Something went wrong");
- }
-
-
-
- catch (Exception ex) when (ex.Message.Substring(0, 7) == "Warning")
- {
-
- }
- catch (Exception ex)
- {
- await LogDataAsync("Oops error occuered => ", ex);
- }
- finally
- {
- await LogDataAsync("Exception Logging Completed.", null);
- }
- }
- public static async Task LogDataAsync(string message, Exception exception)
- {
- using (var file = File.AppendText("issue.log"))
- {
- await file.WriteLineAsync($"{message} {exception?.ToString()}");
- }
- }
- }
Auto properties initializer
You will likely appreciate auto-property initializers. Just as the name implies, you can initialize auto-properties default values with a little less work than you did in the past. C# 6.0 introduces a new feature, auto-property initializers. We no longer need a constructor, because in the back end, the compiler is assigning this value to a backing field. Have a look at the below code snippet.
- public class Employee
- {
-
- public Employee()
- {
- EmployeeId = 10001;
- Name = "Jignesh";
- City = "Bangluru";
- }
-
-
- public int EmployeeId { get; set; } = 100000;
- public string Name { get; set; } = "Jignesh";
- public string City { get; set; } = "Bangluru";
- }
Using getter only auto properties
Getter-only auto-properties are essentially read-only properties that let you omit a setter, leaving you with just the get. And as a result, the backing field of a getter-only auto-property becomes read-only. And just like we just saw in the above example, we can also initialize it with a value. But now, with getter-only auto-properties, your class can remain immutable and you can still get the convenience of the concise syntax of an auto-property.
- public class Employee
- {
-
- public Employee()
- {
- EmployeeId = 10001;
- Name = "Jignesh";
- City = "Bangluru";
- }
-
-
- public int EmployeeId { get; } = 100000;
- public string Name { get; } = "Jignesh";
- public string City { get; } = "Bangluru";
- }
Converting to expression-bodied function member
Expression-bodied function members can work for both methods and properties if you have a method with one statement, and that statement can be represented as an expression.
Expression-bodied function members allow methods, properties and other kinds of function members to have bodies that are expressions instead of statement blocks, just like with lambda expressions.
- class Program
- {
- public string FirstName { get; set; }
- public string LastName { get; set; }
-
- public string GetFullName(string firstName, string lastName) => firstName + lastName;
- static async void Main(string[] args)
- {
- Program program = new Program();
-
- Console.WriteLine(program.GetFullName("jignesh", "Kumar"));
-
- Console.ReadLine();
- }
-
- }
Using Static
Using static is a new kind of using clause that lets you import static members of types directly into scope. In the below example we have used system.Console class using name space so we can directly use WriteLine method in our code where ever we want.
- using System;
- using System.Console;
- namespace CSharpFeatures
- {
- static void Main(string[] args)
- {
- WriteLine("This message from WriteLine function");
- }
That's it from my end!!!
Thank you .... I hope you have enjoyed reading my blog.
If you have any question or queries please feel free to ask and post comments below so I can answer your query.