views:

117

answers:

3

I'm getting a stack overflow when tryin to set a public property in a MasterPage from an ASPX page.

I'm making a "greeting card" editor, using a TabContainer. Each tab has a user control, and everything is updated when active tab is changed - while doing so I need to store all the data away in master page properties.

From the ASPX page:

protected void tcTabs_ActiveTabChanged(object sender, EventArgs e)
{
    Master.Message = "blahblah";
}

From the MasterPage:

public string Message
{
    get { return Message; }
    set { Message = value; }
}

And this is where I get a stack overflow; in the set {}. Doesn't really matter what I try to set, I get the same problem every time. I'm sure I'm missing some minor thing, but as far as I can see I'm following all the examples I've found.

+8  A: 

The problem is that the Message property is calling itself. You need to set a member variable or control property.

Edit: example:

string mMessage = string.Empty;

public string Message
{
    get { return mMessage; }
    set { mMessage = value; }
}
Kieron
+1, or use an auto-property if possible (c# >= 3.0) : public string Message { get; set; }
ybo
Yeah, good point.
Kieron
Thanks, I knew it was some kind of n00b error.
Marcus L
That's why SO is here (: Good luck
Kieron
+1  A: 

Kieron is correct, your property is essentially an infinite recursive method call. Your property gets compiled to something like this:

public string get_Message() { return get_Message(); }
public void set_Message(string value) { set_Message(value); }

Which is obviously not correct. You need a backing field:

private string message;
public string Message { get { return this.message; } set { this.message = value; } }

Or if you're working with C# 3, just define Message like so:

public string Message { get; set; }
Rytmis
+1 for good explanation.
Marcus L
A: 

Buddy, whenever you're not using automatic properties

public string Message{get;set;}

You need to have some private variable or some variable where you can store the value of the property... Usually I do this

private string _Message;

public string Message { get{return _Message;} set{_Message = value;} }

Simple? Si.

Cyril Gupta