Skip to content

Out variables C# 7.0correctnesscode reduction

Declare out parameters inline.

When using out parameters it can be often advantageous to declare them right inline with the out argument itself. This reduces the line count, allows var to be used to infer the type from the method signature and prevents the variable being accidentally assigned or reused before the call.

Code ​

csharp
if (int.TryParse(txtQuantity.Value, out var quantity))
{
    order.Quantity = quantity;
}
csharp
int quantity;
if (int.TryParse(txtQuantity.Value, out quantity))
{
    order.Quantity = quantity;
}

Notes ​

  • A variable declared in an if condition is still in scope after the if statement, so it can be used in the code that follows
  • Use a discard C# 7.0 out _ when you don't need the value at all
  • Expression variables in initializers C# 7.3 allows out variables in field, property and constructor initializers and query clauses

More information ​

Powered by Intracia