Tag Archives: C# 7

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:

            Console.WriteLine("How old are you?");
            string input = Console.ReadLine();

            int x = 0;
            if (int.TryParse(input, out x))
                Console.WriteLine("You don't look {0}!", x);
            else
                Console.WriteLine("That doesn't sound quite right.");

            Console.ReadLine();

That x declaration is a little annoying – it wastes a line just to declare a variable so that we can get an out parameter into it. In C# 6, we can finally get rid of it:

            Console.WriteLine("How old are you?");
            string input = Console.ReadLine();

            if (int.TryParse(input, out int x))
                Console.WriteLine("You don't look {0}!", x);
            else
                Console.WriteLine("That doesn't sound quite right.");

            Console.ReadLine();

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:

  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
    <PlatformTarget>AnyCPU</PlatformTarget>
    <DebugSymbols>true</DebugSymbols>
    <DebugType>full</DebugType>
    <Optimize>false</Optimize>
    <OutputPath>bin\Debug\</OutputPath>
    <DefineConstants>DEBUG;TRACE</DefineConstants>
    <ErrorReport>prompt</ErrorReport>
    <WarningLevel>4</WarningLevel>
    <LangVersion>Experimental</LangVersion>
  </PropertyGroup>

Now, I particularly love this feature because I use concurrent collections a lot. And those are full of out parameters. Here’s an example using a ConcurrentDictionary:

            var dict = new ConcurrentDictionary<string, Guid>();
            bool added = dict.TryAdd("user1", Guid.NewGuid());

            bool retrieved = dict.TryGetValue("user1", out Guid user1Guid);
            Console.WriteLine(user1Guid);

            Console.ReadLine();

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:

            foreach (var num in var numbers = Enumerable.Range(1, 10))
                Console.WriteLine("Processing {0} of {1}...", num, numbers.Count());

…and here’s the output of that, just so you get the idea:

Processing 1 of 10...
Processing 2 of 10...
Processing 3 of 10...
Processing 4 of 10...
Processing 5 of 10...
Processing 6 of 10...
Processing 7 of 10...
Processing 8 of 10...
Processing 9 of 10...
Processing 10 of 10...

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:

from s in strings
select int.TryParse(s, out int i) ? i : -1;