C# 6.0 – Declaration Expressions

UPDATEIt was decided that Declaration Expressions would not make it into the final release of C# 6.0 and they no longer work in Visual Studio 2015 Preview.

This is another post in the series on the new features that are coming in C# 6.0.

This is a complex name for a simple concept. Until now, if you ever wanted to use an out parameter in a method, you had to declare it before using it.

We’ve all written code like this,

int i;
if (Int32.TryParse(value, out i))
    // Use i here

Now you can write the much simpler,

if (Int32.TryParse(value, out var i))
    Assert.That(i, Is.EqualTo(expected));

There are a couple of things to note here. First is that i is only in scope within the if statement. You cannot use it outside the if statement. Second, notice that I used var and that the type was correctly infered as int.

It is also useful for casting. You no longer have to cast an object as something, then check if it is null. You can now do it all within the if statement.

if ((string str = obj as string) != null )

It can also be useful for quickly supplying default args for a TryParse.

int x = Int32.TryParse(value, out var i) ? i : -1;

Sweet and simple…

If you want to check out the code for this series of posts, it is on GitHub at https://github.com/rprouse/CSharp60.