C# 6 Preview: Declaration Expressions

Note: although this feature appears to be implemented as an experimental language feature in Visual Studio 14 CTP4, the Roslyn language features page seems to indicate that it won’t be supported. In fact this post seems to confirm that declaration expressions won’t make it into the next version of .NET. Keep this in mind as you continue reading.

Update 14th April 2017: Although this feature did not make it into C# 6, it is now available as from C# 7 (released in 2017).

One of the new features in C# 6 is that we’ll be allowed to declare a variable from within an expression. The most common example of this is in the out parameter of a TryParse() call. Consider this code:

To actually get this working in Visual Studio 14 CTP4 (which is the latest at the time of writing this article), you’ll need to set the LangVersion to Experimental by editing the .csproj file in a text editor and adding the line highlighted below:

Now, declaration expressions are useful for more than just out parameters. In fact, if you read Scott Allen’s article on the subject, you’ll see a couple of examples of declarations within conditional and loop expressions. Below is an example of how declaration expressions may be used in a loop:

Finally, here is an example from the Roslyn C# feature descriptions (CTP3) [PDF] which shows how declaration expressions can facilitate the use of out parameters in queries, where declarations were previously not possible: