tags:

views:

52

answers:

1

So...this one has me stumped. I am using VS 2008 (C#).

I have some code that is infinitely recursive, but for the life of me I can't reason why (well, I have a guess). You can reproduce the problem by doing this:

  1. Create a new Form or UserControl class. Add a child control (button, label, whatever) to it.
  2. Open the code file. Override the Font property and make it return and set the child control's Font property, i.e.,

    class MyForm
    {
        public override Font Font
        {
            get { return childControl.Font; }
            set { childControl.Font = value; }  // not actually needed to reproduce 
        }
    }
    

    You only need the getter to return the child control's property to reproduce the problem. After the next build do not open the designer for your Form or UserControl, VS will crash.

  3. Start your program. It will crash due to a StackOverflow. This happens on the

    this.Controls.Add( childControl );
    

    line of the designer file. The Get() call to the Font property is recursive.

So, does anyone know why returning the child control's property in an override cause a stack overflow when the child is added to the Controls collection?

+4  A: 

That's because getting a control's font involves looking at the parent's font, which in your case involves looking at the child's font, which involves looking at the parent's font, which involves...

From MSDN:

The Font property is an ambient property. An ambient property is a control property that, if not set, is retrieved from the parent control.

HTH, Kent

Kent Boogaart