Search code examples
c#out

Modifying C# Out parameter more than once


When you have a function that has an out parameter is it best practice to create a new variable inside the function and assign the out parameter to it at the end of the function? Or give the out parameter some empty/default value in the beginning and modify throughout the function.

I'm trying to come up with some reasoning as to why one of these coding styles/practices is better to use.

Option 1: Using just the out parameter.

public bool SomeFunc(out string outStr)
{
   outStr = "";

   if (errorCond)
      return false;

   outStr += "foo";
   outStr += "bar";

   return true;
}

Option 2: Using a temporary variable.

public bool SomeFunc1(out string outStr)
{
   string tempStr = "";
   outStr = "";      // To prevent 'The out parameter must be set' error on return false line.

   if (errorCond)
      return false;

   tempString += "foo";
   tempString += "bar";

   outStr = tempStr;
   return true;
}

Even though both of these achieve the same outcome, which is preferable? Are there any drawbacks to either one of them?


Solution

  • Actually, it doesn't matter, you just must assign variable in this method. But, it is preferable to avoid using output or reference parameters:

    Working with members that define out or reference parameters requires that the developer understand pointers, subtle differences between value types and reference types, and initialization differences between out and reference parameters.

    For me, the second one is overhead

    Assign a default value at the beginning of the method, and then change the value if necessary.

    Look at examples in .net source codes, like int.TryParse or Enum.TryParse