Search code examples
c#argument-passing

Can you use the variable of an out parameter as the next argument to another function in the same expression as the call which sets the out parameter?


Is this code safe, and will it do what I expect? Are there any pitfalls? Is it necessary that GenerateValue use a ref parameter, or would the method taking that argument by value also work?

 int value;
 UseValue(GenerateValue(out value), ref value);

Method definition should not affect the answer, but here is an example definition:

    private bool GenerateValue(out int value)
    {
        bool success = true;
        value = 42;
        return success;
    }

    private void UseValue(bool success, ref int value)
    {
        if (success)
        {
            System.Diagnostics.Debug.WriteLine(value);
        }
    }

Solution

  • The code is safe. Basically it is equivalent of

    int value;
    bool res = GenerateValue(out value);
    UseValue(res, ref value);
    

    Please note, as @sstan commented, that ref is not really needed in our case. But even if it would be needed due to change of value inside Usevalue, the code still stays OK.