So Su Team : Web Development Tags : Web Development Programming

New language features for C#

So Su Team : Web Development Tags : Web Development Programming

A preview of the new language features in the next update to C# was released at BUILD back in March with the announcement of the open source compiler Roslyn. The features have been refined since then and are still undergoing design and discussion.

I won't cover all the new language features, as most of them are just syntactic sugar. Here are the ones that stand out for me.

Exception Filters

In a try catch block you can execute specific code based on the type of exception thrown. With Exception filters are catch blocks are supplemented with an 'if' condition. So you can execute different code based on specific values from the exception. I like it. Its a new feature that doesn't have an equivalent.

try
{
    throw new ArgumentNullException("myParam");
}
    catch (ArgumentException e) if (e.ParamName == "otherParam")
{
    Console.WriteLine(e.Message);
}
catch (Exception e)
{
    //all other exceptions
}

Primary Constructors

My initial reaction to this was "why?"! I think this is a terrible feature. It makes classes look like methods, and confuses things even more so with "initialisation scope" where variables can exist with the same name. I mean lets look at this bit of code:

public class Family(Person mum, Person dad)
{
    private Person dad = dad;
    private Person oldestChild = (var babies = b.GetBabies().OrderBy(x => x.Age)).Last();
    private Person youngestChild = babies.First();
}

What the!? I'm fighting decades of programming experience trying to understand this code. I have to know special rules for this initialisation scope because now, its different to a normal scope.

Null propagation

Great feature. It's essentially syntactic sugar for null checking against parameters, but makes your code very much more readable.

Before:

if (a != null)
{
    if (a.b != null)
    {
        return a.b.c;
    }
}
return null;

After:

return a?.b?.c;

Although there are lots of new small changes coming up, there's nothing all that major. In previous updates we've had dynamics and parallelism, but this update is lacking something that big (so far). Check out the status of all the features here: Roslyn.