OdeToCode IC Logo

C# 6.0 Features Part 3: Declaration Expressions

Monday, September 15, 2014

Update: this feature was dropped from C# 6.0. 

In C# we’ve always had declaration statements for declaring variables, and expression statements to produce values.

In C# 6 we can mix a declarations with an expression to declare a new variable and produce a value.

The canonical example is the int.TryParse method, which requires an out parameter. In previous versions of C# the parameter would be declared in a distinct statement before the invocation of TryParse.

int result;
if(int.TryParse(input, out result))
{
    return result;
}
return 0; // note: result still in scope

With C# 6.0, the same result is achievable with a declaration expression. The declaration statement also limits the scope of the variable passed as an out parameter.

if (int.TryParse(input, out var result))
{
    return result;
}
return 0; // result is out of scope

We could also transform the above code into a one-liner. . .

return int.TryParse(input, out var result) ? result : 0;

. . . and then package it into an extension method for string.

public static int ParseIntSafe(this string input, int @default = 0)
{
    return int.TryParse(input, out var result) ? result : @default;
}

With declaration expressions we can also declare variables inside if statements . . .

if ((var address = user.HomeAddress) != null)
{
    // work with address ...

    return address.City;
}

. . . and the various looping statements.

int result = 0;
foreach (var n in var odd = numbers.Where(n => n % 2 == 1).ToList())
{ 
    result += n + odd.Count();
}
return result;

Declaration are a small addition to the C# language, but will come in useful in a few scenarios.