[C#] Cleaning Up Code by Inlining Method Argument Definitions with Out Variable Declarations

Introduced in C# 7.0, Out variables allow you to declare a variable directly within the argument list when calling a method that has an out parameter.

This eliminates the need to write a separate line to declare the variable beforehand, as was required previously. This reduces the amount of code and allows for a smoother logical flow. It is particularly effective when using TryParse methods or Dictionary.TryGetValue.

In this article, I will explain its specific usage using an example of converting a string to a number.

目次

Table of Contents

  1. Implementation Example: Usage in TryParse
  2. Specifications and Benefits of Out Variable Declarations
  3. Summary

Implementation Example: Usage in TryParse

Below is a program that converts user input (a string) into a number (double). By writing out var result inside the arguments of double.TryParse, we perform both the variable declaration and the receipt of the result simultaneously.

using System;

namespace OutVariableExample
{
    class Program
    {
        static void Main(string[] args)
        {
            // String to be converted
            string inputString = "123.456";

            Console.WriteLine($"Input string: \"{inputString}\"");

            // [Point]
            // By writing 'out var result' inside the method argument,
            // you can perform variable declaration and method call in a single line.
            // Previously, a declaration like 'double result;' was required before this line.
            if (double.TryParse(inputString, out var result))
            {
                // On success, the declared variable 'result' is available within this block
                Console.WriteLine($"Conversion success: Value is {result}.");
                
                // Can be used directly for calculation
                Console.WriteLine($"Doubled value: {result * 2}");
            }
            else
            {
                Console.WriteLine("Conversion failed. Not a numeric format.");
            }

            // Reference: Example with another type (int)
            // It is also possible to write the type explicitly instead of using type inference (var)
            string intInput = "999";
            if (int.TryParse(intInput, out int intValue))
            {
                Console.WriteLine($"Integer conversion: {intValue}");
            }
        }
    }
}

Specifications and Benefits of Out Variable Declarations

1. Reducing Lines of Code and Improving Readability

In the older style (C# 6.0 and earlier), variable declaration and usage were separated.

// Old Style
double result; // Pre-declaration required
if (double.TryParse(inputString, out result))
{
    // ...
}

By using out variable declarations, the variable is declared “immediately before receiving the value.” This makes the variable’s purpose clear and eliminates the need to consider unintended initial values.

2. Variable Scope

The scope of an out variable declared within an if statement’s condition is not limited to just that if block. It extends to the enclosing block (in this case, the entire Main method). Therefore, it is possible to use the variable outside the if block as shown below:

if (double.TryParse("3.14", out var value))
{
    // Processing on success
}
// 'value' can be referenced here as well 
// (Note: Be careful as it might contain the default value if conversion failed)
// Console.WriteLine(value); 

Summary

Out variable declarations are a small feature, but they can drastically clean up frequently used patterns like TryParse or dictionary lookups (TryGetValue).

  • Syntax: Method(out var variableName) or Method(out Type variableName)
  • Effect: Eliminates the need for prior variable declaration.
  • Use Case: When you want to define a variable on the spot to receive a result.

Use this actively to avoid redundant code and focus on the core logic.

よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!

この記事を書いた人

私が勉強したこと、実践したこと、してることを書いているブログです。
主に資産運用について書いていたのですが、
最近はプログラミングに興味があるので、今はそればっかりです。

目次