Home > Articles > Programming > C#

A Brief Tour of C# 6.0

  • Print
  • + Share This
Like this article? We recommend 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

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020