Skip to content

Expression variables in initializers C# 7.3code reduction

Use `out var` and pattern variables in field initializers, constructor initializers, and LINQ queries.

C# 7.0 introduced out variables and pattern matching which allowed declaring variables inline. However, these expression variables were not permitted in field initializers, constructor initializers (this() / base()), or LINQ query clauses.

C# 7.3 removes these restrictions, allowing expression variables to be used in these additional contexts.

Code ​

csharp
class Order
{
    // Out variable in field initializer
    readonly int maxItems = int.TryParse(Config.MaxItems, out var n) ? n : 10;

    public Order(int id) { /* ... */ }

    // Out variable in constructor initializer
    public Order(string input) : this(int.TryParse(input, out var id) ? id : 0)
    {
    }
}

// Out variable in LINQ query clause
var results = from s in strings
              where int.TryParse(s, out var n) && n > 10
              select s;
csharp
class Order
{
    readonly int maxItems = ParseOrDefault(Config.MaxItems, 10);

    public Order(int id) { /* ... */ }

    public Order(string input) : this(ParseOrDefault(input, 0))
    {
    }

    // Had to move the parsing into a helper method
    static int ParseOrDefault(string s, int fallback) =>
        int.TryParse(s, out var n) ? n : fallback;
}

// Had to switch to method syntax with a lambda
var results = strings.Where(s => int.TryParse(s, out var n) && n > 10);

Notes ​

  • Variables declared this way are scoped to the initializer or query clause they appear in, so n above cannot be used in the select
  • The restriction existed because a field or constructor initializer has no local variable scope to declare into, and a query clause is translated into a lambda before scoping is decided
  • A method-syntax lambda does allow an out variable inside its body, so the workaround in the before example was about clause scoping rather than a hard limitation
  • The declaration is still an ordinary local in the generated code, so it is not captured beyond the expression that declares it
  • Field initializers run before the constructor body, so an out variable there sees only static state available at that point
  • See out variables C# 7.0 for the inline declaration form this extends

More information ​

Powered by Intracia