#1,219 – C# 6.0 – Filtering Exceptions

C# 6.0 will include support for exception filters, that is–only catching a particular type of exception if an associated expression evaluates to true.

You can filter exceptions by including a when statement after the catch expression.  If the result of evaluating the expression supplied is true, the exception is caught.  If not, the behavior is as if you didn’t supply a catch block.

In the example below, we don’t catch divide by zero exceptions on Saturdays.

            int denom;
            try
            {
                denom = 0;
                int x = 5 / denom;
            }
            // Catch /0 on all days but Saturday
            catch (DivideByZeroException xx) when (DateTime.Now.DayOfWeek != DayOfWeek.Saturday)
            {
                Console.WriteLine(xx);
            }

#1,218 – C# 6.0 – Using Expression-Bodied Property Getters

In addition to using expression-body definitions for method bodies in C# 6.0, you can use an expression-body definition to implement the getter of a read-only auto-property.

For example:

        public string Name { get; protected set; }
        public int Age { get; set; }

        public string BackwardsName => new string(Name.Reverse().ToArray());

The presence of the expression-body definition tells the compiler that this is a property with a getter, rather than a field.

#1,217 – C# 6.0 – Using Expression-Bodied Methods

In C# 5.0, you could use a lambda expression wherever a delegate instance was expected.  For example:

            Func doubleMyNumber = (i) => 2 * i;

In C# 6.0, you use something similar for the body of a function member, known as an “expression-body definition” to define the method. This simplifies the syntax for simple methods.  For example:

    public class Dog
    {
        public Dog(string name, int age)
        {
            Name = name;
            Age = age;
        }

        public string Name { get; protected set; }
        public int Age { get; set; }

        public void AgeIncrement() => Age++;
        public int AgeInDogYears() => Age * 7;
    }

#1,216 – C# 6.0 – Initializing Read-Only Auto-Properties from Constructors

In C# 6.0, when defining a read-only auto-property you can initialize the property as part of its declaration.

  public DateTime DogCreationTime { get; } = DateTime.Now;

You can also initialize these read-only auto-properties from a constructor.  For example:

    public class Dog
    {
        public string Name { get; }

        public Dog(string name)
        {
            Name = name;
        }
    }

#1,215 – C# 6.0 – New Syntax for Dictionary Initializers

Prior to C# 6.0, you could initialize a Dictionary object with a collection initializer as follows:

            // Initialization with collection initializer
            Dictionary<string, int> guys = new Dictionary<string, int> {
                {"Galileo", 1564},
                {"Magellan", 1480},
                {"Voltaire", 1694},
                {"Kepler", 1571},
                {"Keaton", 1895}
            };

In C# 6.0, the following syntax will also work:

            // Initialization with new dictionary initializer
            Dictionary<string, int> guys = new Dictionary<string, int>
            {
                ["Galileo"] = 1564,
                ["Magellan"] = 1480,
                ["Voltaire"] = 1694,
                ["Kepler"] = 1571,
                ["Keaton"] = 1895
            };

Note that as of 29 Oct, 2014, this feature is not enabled in the current Visual Studio 2014 CTP.

#1,214 – C# 6.0 – using Directive with Static Class

In C# 6.0, you can use a using directive not only with namespace names, but also with the name of a static class.  This allows invoking static methods in the class without having to specify the class name.

For example, assume that we have a static class Utility with an AddInts method.  Assume also that Utility is defined within a namespace having the name SomeNamespace.  In C# 5.0, you’d do the following to call the method:

using System;
using SomeNamespace;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            int sum = Utility.AddInts(5, 2);

            Console.ReadLine();
        }
    }
}

In C# 6.0, you can include the class name in the using directive and omit it when invoking the method.

using System;
using SomeNamespace.Utility;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            int sum = AddInts(5, 2);

            Console.ReadLine();
        }
    }
}

#1,213 – Visual Studio 2015 – Unused using Statements Greyed Out

In Visual Studio 2015, the editor will grey out any using statements that are not required.  This is done at build time.  Note that you can still use the Remove Unused Usings command to remove any unused statements.  (This command has been renamed Remove Unnecessary Usings).

Below, all but the first using statement is greyed out, since the code that follows makes no use of types from any of the other namespaces.

1213-001

 

#1,212 – List of Features Shipping in C# 6.0

Thanks to Steve Hall for pointing out the location of the following information.

You can get the current status of all language features that will be present in the upcoming C# 6.0 release, as part of the Roslyn compiler platform project.  Here’s the link to the page on GitHub containing a current list of features:

Language features in C# 6 and VB 14

For reference, below is the list of planned C# 6.0 language features, as of 1 Apr, 2015.

Features that are “done” (already implemented):

  • Auto-property initializers
  • Getter-only auto-properties
  • Constructor assignment to getter-only auto-properties
  • Parameterless struct constructors (more info)
  • Using static members
  • Dictionary initializer
  • Await in catch/finally
  • Exception filters
  • Expression-bodied members
  • Null propagation
  • String interpolation
  • nameof operator
  • #pragma
  • Extension Add in collection initializers
  • Improved overload resolution

#1,211 – C# 6.0 – Adding Implementation for a Primary Constructor

NOTE: Primary constructors will not be shipping in C# 6.0, after all.  They were implemented in the language, but did not yet have appropriate downstream work done in time for the release of 6.0 (i.e. in Visual Studio and debugger).  Thanks to Steve Hall for pointing this out.  –SPS, 23Oct14

A primary constructor in C# 6.0 allows declaring constructor parameters as part of the type declaration and then using those parameters within auto-property initializers.

You can optionally include an implementation body for the primary constructor, typically at the start of the type.  The implementation includes a code block without any method name or parameters.

Below, the primary constructor implementation derives the value of one property from the name parameter and does some validation on the age parameter.

    public class Dog(string name, int age)
    {
        {
            Name = name + " the Dog";
            if (age > 20)
                throw new ArgumentException("Age too large");
        }

        public string OrigName { get; } = name;
        public string Name { get; protected set; }
        public int Age { get; set; } = age;
    }

1211-001

#1,210 – C# 6.0 – Primary Constructors

NOTE: Primary constructors will not be shipping in C# 6.0, after all.  They were implemented in the language, but did not yet have appropriate downstream work done in time for the release of 6.0 (i.e. in Visual Studio and debugger).  Thanks to Steve Hall for pointing this out.  –SPS, 23Oct14

C# 6.0 introduces the notion of a primary constructor–a constructor defined as part of the type declaration, rather than as a separate method.

Consider the C# 5.0 example below, with a traditional constructor that initializes a couple of properties.  (Note that Name property is not immutable, but only protected).

    public class Dog
    {
        public Dog(string name, int age)
        {
            Name = name;
            Age = age;
        }

        public string Name { get; protected set; }
        public int Age { get; set; }
    }

The primary constructor syntax allows us to simplify this code, moving the constructor into the class declaration.  We can then use auto-property initializers that reference the constructor’s parameters.

    public class Dog(string name, int age)
    {
        public string Name { get; protected set; } = name;
        public int Age { get; set; } = age;
    }

This second code fragment behaves exactly like the first.