#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);
            }
Advertisement

#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;
    }