Out Parameter in Recursive Function

Hi,

I have a function that adds elements from tree to a list recursively.
I would like to put the list initialization inside the implementation of the function (There's no good reason, just to understand how)
and pass the list argument as out parameter.

The thing is when I do it I get the error saying I must assign value, because I only initialize the list the first time if it is null the else condition doesn't have initialization.
How should I write it.

Here's the pseudo code:

public func(Tree root, out IList list)
{
.....
if (root == null)
      return;
if (list == null)
      list = new List();
func(root.child,out list);
....
}

breezbackAsked:
Who is Participating?
 
RishadanPortConnect With a Mentor Commented:
the "out" key requires that in each function call, the "out" variable is changed.
0
 
RishadanPortCommented:
maybe instead use the ref key?

public func(Tree root, ref IList list)
{
.....
if (root == null)
      return;
if (list == null)
      list = new List();
func(root.child,ref list);
....
}
0
 
RishadanPortCommented:
I should get credit for this question, as the answer I specified is correct.
0
 
RishadanPortCommented:
Thanks
0
All Courses

From novice to tech pro — start learning today.