tags

C# 6

Exception filters in C# 6: their biggest advantage is not what you think

Exception filters are one of the major new features of C# 6. They take advantage of a CLR feature that was there from the start, but wasn’t used in C# until now. They allow you to specify a condition on a catch block: static void Main() { try { Foo.DoSomethingThatMightFail(null); } catch (MyException ex) when (ex.Code == 42) { Console.WriteLine("Error 42 occurred"); } } As you might expect, the catch block will be entered if and only if ex.

Customizing string interpolation in C# 6

One of the major new features in C# 6 is string interpolation, which allows you to write things like this: string text = $"{p.Name} was born on {p.DateOfBirth:D}"; A lesser known aspect of this feature is that an interpolated string can be treated either as a String, or as an IFormattable, depending on the context. When it is converted to an IFormattable, it constructs a FormattableString object that implements the interface and exposes:

StringTemplate: another approach to string interpolation

With the upcoming version 6 of C#, there’s a lot of talk on CodePlex and elsewhere about string interpolation. Not very surprising, since it’s one of the major features of that release… In case you were living under a rock during the last few months and you haven’t heard about it, string interpolation is a way to insert C# expressions inside a string, so that they’re evaluated at runtime and replaced with their values.