In the code below, the StylusPointCollection (SPC) changes according to whether I declare the StylusPoint variable inside or outside the method (i.e. if I comment the internal definition and uncomment the commented lines) . I don’t understand why this is.
//StylusPoint spXY;
private void DrawBinaryTree(int depth, StylusPoint pt, double length, double theta)
{
if (depth > 0)
{
StylusPoint spXY = new StylusPoint(pt.X + length * Math.Cos(theta) * Math.Cos(a), pt.Y + length * Math.Sin(theta) * Math.Sin(a));
//spXY = new StylusPoint(pt.X + length * Math.Cos(theta) * Math.Cos(a), pt.Y + length * Math.Sin(theta) * Math.Sin(a));
SPC.Add(pt);
SPC.Add(spXY);
DrawBinaryTree(depth - 1, spXY, length * lengthScale, theta + deltaTheta);
DrawBinaryTree(depth - 1, spXY, length * lengthScale, theta - deltaTheta);
}
}
I have tried and failed to come up with a more simple example using LinqPad.
The difference stems from the fact that you make two recursive calls to the function trying to pass the variable in question to both. When you declare the variable outside the function, it gets modified by each call to
DrawBinaryTree. When you declare the variable local, each call toDrawBinaryTreegets its own copy of the variable that other calls cannot modifyWith a local:
With a global: