Home > Articles > Programming > C#

  • Print
  • + Share This
From the author of Improvements to Existing Features

Improvements to Existing Features

I'll begin with a feature many developers thought C# already supported: using the await keyword in a catch or finally clause. Developers might have thought this feature was already supported because the await expression had so few restrictions on where it can be used. The C# language team did quite a bit of work in C# 5.0 trying to make async and await work seamlessly with all the remaining features in the C# language. That was a laudable goal, but the reality is that introducing an await expression in a catch or finally clause is very hard on the compiler. The language designers always wanted this feature; it just didn't make the time schedules for C# 5.0. Now, with the new C# 6.0 codebase, the team prioritized this addition to the async and await features. For example, examine this code snippet:

private async static Task RunAsyncTest()
{
    try
    {
        await DoWebbyThings();
    }
    catch (Exception e)
    {
        await GenerateLog(e.ToString());
        throw;
    }
}

This method will return a task. If an exception is thrown from DoWebbyThings(), the method returns a task that will eventually return a faulted task. Faulted tasks contain an aggregate exception that contains any exceptions generated during the execution of the task. If the GenerateLog message completes correctly, the AggregateException contains a single exception: the exception thrown by DoWebbyThings(). However, if GenerateLog() throws an exception, the AggregateException still contains a single exception: the exception thrown by GenerateLog(). The behavior I've just described is how this works for an await in either a catch or a finally clause. This feature may not change your daily coding experiences very much, but it means that C# more naturally supports async programming in more situations and scenarios. The behavior is consistent with how task objects are processed in other areas of your code.

Another changed feature is using static members. This is an extension to the using statements that import definitions into the current (or global) namespace. Every C# developer is familiar with the classic using statements:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

Now you can limit the scope of a using statement to a single static class:

using System.Math;

Notice that the syntax highlighting shows that System.Math is a class, not a namespace. This new variation of the using statement enables you to reference members of a static class (such as Math) simply by their names:

var answer = Sqrt(3 * 3 + 4 * 4);

This feature is clear if you're using static methods from a class. However, the features works a bit differently for methods used as extension methods. Consider this query:

var results = from n in Enumerable.Range(0, 20)
                where n % 2 == 1
                select new { n, square = n * n };

The code works perfectly as long as you include this:

using System.Linq;

However, suppose you want to use this new feature:

using System.Linq.Enumerable;

You might think you could change the query to look like this:

var results = from n in Range(0, 20)
                where n % 2 == 1
                select new { n, square = n * n };

This version of the query fails with the following message:

Could not find an implementation of the query pattern for source type 
'System.Collections.Generic.IEnumerable<int>'.  'Where' not found.  
Are you missing a reference to 'System.Core.dll' or 
a using directive for 'System.Linq'? 

This new feature, using static classes, will not find extension methods. That restriction was added specifically for LINQ. The development team wanted to make sure that developers didn't accidentally change queries from IQueryable to IEnumerable. If you wanted to use this feature, you would need to rewrite the query to use the static methods. In general, I would recommend against that approach.

This is also a small feature enhancement. It enables you to write cleaner code with less ceremony. You don't need to type the class name whenever you reference static methods in a static class. It could lead to extra confusion, however, because without that extra scoping information it may be hard to know where a method lives. In practice, that isn't an issue, because IntelliSense shows you the class name when you roll over a call to one of these methods.

Next, we have the null propagation operator (?.). The null propagation operator provides a succinct way to test a variable against null and take some action if it's not null. One of the primary scenarios for the null propagation operator is to simplify chaining members of objects. Consider the following simplified class relationship:

public class Company
{
    public Person ContactPerson { get; set; }
}
public class Person
{
    public Address HomeAddress { get; set; }
}
public class Address
{
    public string LineOne { get; set; }

}

Using the null propagation operator, you can access the first line of the contact person's home address by using this simple syntax:

var vendor = new Company();
// elided
var location = vendor?.ContactPerson?.HomeAddress?.LineOne;

If any of the properties are null, the value of location is null. However, if ContactPerson, HomeAddress, and LineOne are all non-null, the value of location will be the string containing the first line of the address.

Prior to the advent of this feature, you would have had to write the following for equivalent access:

var vendor = new Company();
// elided
var oldStyleLocation = default(string);
if (vendor != null)
{
    if (vendor.ContactPerson != null)
    {
        if (vendor.ContactPerson.HomeAddress != null)
        {
            oldStyleLocation = vendor.ContactPerson.HomeAddress.LineOne;
        }
    }
}

This old-style code creates that "staircase effect" that eventually leads to difficulties in understanding for all but the simplest uses.

The null propagation operator has other uses as well. Suppose you aren't sure if an object supports IDisposable. You can safely attempt to dispose of the object by using the null propagation operator:

object obj = new Company();

(obj as IDisposable)?.Dispose();

The null propagation operator can be abused, just like the conditional operator can—but that's true of any language feature. Rather than concentrating on how this feature could be abused, I've been considering how this new feature could make my code more readable and clear. Used with some restraint, this feature makes it easy to see how fields, properties, or variables relate to each other, and what default value should be used if any of them are null.

One more feature in C# 6.0 might surprise developers who thought it was already implemented: exception filters. This feature has been part of the Visual Basic.NET language for some time. Adding it to C# is part of the co-evolution strategy on which Microsoft embarked several years ago. Exception filters enable you to put extra logic on your catch clauses. In addition to matching a particular type of exception, an exception filter provides extra conditions on an exception to see whether it should be processed. Exception filters are very useful for scenarios in which different error conditions throw the same type of exception. One common scenario is the WebException class. It indicates some error communicating with a remote resource, but any number of errors could cause that exception. Suppose you only want to respond to errors involved in setting up a secure channel. You can add the following filter:

try
{
    var result = await someWebMethod();
}
catch (WebException e) if (e.Status == WebExceptionStatus.SecureChannelFailure)
{
    // Something went wrong with SSL
    WriteLine("SSL Error");
}

You can even add a second catch clause on the same exception type (without the filter) if you have specific actions to take on one error value, but other, more general actions on other errors.

try
{
    var result = await someWebMethod();
}
catch (WebException e) if (e.Status == WebExceptionStatus.SecureChannelFailure)
{
    // Something went wrong with SSL
    WriteLine("SSL Error");
}
catch (WebException e2)
{
    // Some other status failed
    WriteLine("Other WebException error");
}

You can also use this language feature to log exceptions without actually catching them. Create a log method that always returns false:

private static bool logMessage(Exception e)
{
    WriteLine("Logging Exception {0}", e.ToString());
    return false;
}

Then, anywhere you want, add a try/catch block. Catch the base Exception class, but run it through the log filter method:

try
{
    var result = await someWebMethod();
}
catch (Exception e) if (logMessage(e)) { }
catch (WebException e) if (e.Status == WebExceptionStatus.SecureChannelFailure)
{
    // Something went wrong with SSL
    WriteLine("SSL Error");
}
catch (WebException e2)
{
    // Some other status failed
    WriteLine("Other WebException error");
}

Because logMessage() always returns false, the first (empty) catch clause never executes. You can log the error and preserve the original stack, because you don't actually catch the exception. It's a powerful idiom that's also a bit dangerous. I recommend against using exception filters for side-effects in most instances. This use case is an accepted exception (forgive the pun).

  • + Share This
  • 🔖 Save To Your Account