How to assign a parameter to a function?

I have a method that returns an object, and also has an out parameter. A method calls another method that takes the same parameter as another parameter. This gives a build error for the return statement:

Out 'param1' must be set before the current method is removed

The code looks like this:

public TypeA Method1(TypeA param1, out bool param2)
{
  /... some logic here .../
  SubMethod(out param2);
  /... some logic here .../
  return param1;
}

param2 is managed in SubMethod (), not Method1 (). Is there anything else I need to do?

+5
source share
3 answers

In this case, I will assign a default value. Regardless of bool, int, myFoo, etc. - set the default value.

public TypeA Method1(TypeB param1, out bool param2)
{
  param2 = false;   // default value;
  // or
  param2 = default(bool); // in cases where you are not sure what the default is

  /... some logic here .../
  SubMethod(out param2);
  /... some logic here .../
  return param1; // UPDATE: <- this is where you are receiving the exception
}

, "param1", param1 ( : , TypeB : TypeA ).

, param2 out SubMethod(...) param2. param1. , ?

+3

false Method1.

+1

May I suggest moving the out parameter in SubMethod to the return type:

public TypeA Method1(TypeB param1, out bool param2)
{
  /... some logic here .../
  param2 = SubMethod(param2);
  /... some logic here .../
  return param1;
}
0
source

All Articles