Stack Overflow Error in UserControl

H

Harvey

Hello:

I would appreciate if anyone could tell me why the
following occurred in my WinForms app. I am using a User
control and everything was running ok until I defined the
following property:

public int Height
// Height of the control in pixels
{
get
{
return this.Height;
}
set
{
this.Height = value;
}
}


Then, when I made the following call:

this.Height = Math.Max((ctl.Top + ctl.Height),
this.Height);


the stack overflow error would reproducibly occur. Yet
the app compiled without error.

Could someone explain what is going on here? I imagine it
has something to do with property overriding, but if that
is the case, why is not a compilation error thrown?

thanks in advance.

Regards,
Harvey
 
T

Tobin Harris

Harvey said:
Could someone explain what is going on here? I imagine it
has something to do with property overriding, but if that
is the case, why is not a compilation error thrown?

I imagine that the "Height" get property calling itself when you return
this.Height. Therefore, the execution falls into a recursive loop that
cannot exit (until it finally overflows the stack causing an exception!).
Guessing a little, but one idea might be to have your get property call
"base.Height" rather than "this.Height"? Just out of interest, why are you
overriding this property when all it does is what the base class does!?

Hope this helps.

Tobin
 
O

ozbear

Hello:

I would appreciate if anyone could tell me why the
following occurred in my WinForms app. I am using a User
control and everything was running ok until I defined the
following property:

public int Height
// Height of the control in pixels
{
get
{
return this.Height;
}
set
{
this.Height = value;
}
}


Then, when I made the following call:

this.Height = Math.Max((ctl.Top + ctl.Height),
this.Height);


the stack overflow error would reproducibly occur. Yet
the app compiled without error.

Could someone explain what is going on here? I imagine it
has something to do with property overriding, but if that
is the case, why is not a compilation error thrown?

Because your reference to this.Height *inside* the -get-
"calls" the Height property which "calls" the -get-
which "calls the Height property which.....

If you follow the Microsoft member naming guidelines,
the class element should be called height (note the lower
case /h/) and the property name would be Height (note the
upper case /H/).

Inside the property "getter" routine, you would refer to
this.height (note the lower case /h/) to make a direct
reference to the class element, rather than a reference
to the property.

Oz
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top