Setting Properties (correction)

  • Thread starter Thread starter Tina
  • Start date Start date
T

Tina

(on the prior message the code snippet was wrong. this is the one that
executes the set in a loop until a stack overflow occurrs)
(using 1.1)


I have the following property defined in an ascx control.

public string Title //property
{
get {return this.Title; }
set {this.Title = value; }
}

Whan code on a page that contains this control sets the control, for
instance
myControl.title = "this is a heading"
The set executes over and over until a stack overflow occurs.

I am just learning C# and I know there must be something wrong but I don't
have much docs on property setting.

Thanks,
T
 
Hi Tina,

A stack overflow exception occurs when there is an infinite loop. In your
case, you have a property called "Title" that has a get and a set method.
Both methods refer back to the property itself, so it infinitely recurses,
calling it's own get and/or set method whenever it is referenced. Instead,
it should probably refer to a private or protected field, as in:

private string _Title;
public string Title
{
get { return _Title; }
set { _Title = value; }
}

--
HTH,

Kevin Spencer
Microsoft MVP
Professional Numbskull

Complex things are made up of
lots of simple things.
 
You're causing recursion by setting the Title property from within the Title
property "setter" and getting the Title property from within the Title
property "getter". You'll need to store the Title information, for example,
in a field.

private string _title;

public string Title //property
{
get { return _title; }
set { _title = value; }
}
 
You need define a private attribute title to hold the value internally, and
change code to following:

private string title;

public string Title //property
{
get {return this.title; }
set {this.title = value; }
}

Pls note inside get and set, use title, not Title.
Otherwise it will cause a endless loop.

Ryan
 
Back
Top