Blog on Hiatus

The 2,000 Things / C# blog is on hiatus until further notice, due to other commitments that require my time.  Stay tuned..

#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 an if 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) if (DateTime.Now.DayOfWeek != DayOfWeek.Saturday)
            {
                Console.WriteLine(xx);
            }

#1,218 – C# 6.0 – Using Lambdas for Getter-Only Auto-Properties

In addition to using lambda expressions for method bodies in C# 6.0, you can use a lambda expression 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 lambda expression tells the compiler that this is a property with a getter, rather than a field.

#1,217 – C# 6.0 – Using Lambda Expressions for Function Members

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

            Func<int,int> doubleMyNumber = (i) => 2 * i;

In C# 6.0, you can also use a lambda expression as the body of a function member. 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

NOTE: The following is proposed syntax for Roslyn, but not yet working in the Visual Studio 2014 CTP, as of 30 Oct 2014.  The Codeplex site lists this as a “Done” feature for Roslyn, but it’s not absolutely clear whether this will ship with Visual Studio 2014.

In C# 6.0, you’ll be able to define read-only auto-properties you can initialize the property as part of its declaration.

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

The intent in C# 6.0 is that you’ll also be able to 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();
        }
    }
}
Follow

Get every new post delivered to your Inbox.

Join 498 other followers