I have a recursive method which is simplified below:
private List<string> data;
public string Method1()
{
data = new List<string>();
//When Method 1 gets called first time there is a problem
//When Method 1 gets called from Method2 problem is fixed
if (problem)
{
data.Add("prob");
}
if(data.Count > 0)
{
return Method2()
}
else
{
return string.Empty();
}
}
private string Method2()
{
return Method1();
}
When Method1 gets called from Method2 am I right thinking that the data variable is reinitialized wiping out what was previously in there?
When you call
Method1you are creating newList<string>so olddatavariable value becomes inaccessible (will be garbage collected).To avoid it, you have to initialize
datasomewhere outsideMethod1e.g. in constructor.