Search code examples
c#propertiessettergetter-setter

set new value to property in C# web form application


I get this error on the setter line "An unhandled exception of type 'System.StackOverflowException' occurred in WebFormsApplication1.dll" What is an elegant way to manipulate Property1 which I added getter and setter for in a Master page (please see below), then I attempted to manipulate it in method1() and finally call method1() inside onInit.

namespace WebFormsApplication1
{
    public partial class SiteMaster : MasterPage
    {

        public string Property1
        {
            get
            {

                return System.Configuration.ConfigurationSettings.AppSettings["key1"]; 
                //gets value from config file where pair key-value is stored
            }
            set
            {
                Property1 = value;
            }
        }

        public void method1()
        {
            Property1 = Property1 + "stringToAppend"; // manipulate property here
        }

        protected void Page_Init(object sender, EventArgs e)
        {

            method1();

            .....
        }
    }
}

In the Site.Master.aspx I have <%= Property1 %> If I don't add the setter the property is read only. Maybe I should manipulate it inside the setter? I was hoping to be able to do it separately for increased modularisation. Thanks


Solution

  • the problem is here:

    set
    {
        Property1 = value;
    }
    

    You can't do it because recursion occurs here and no condition to exit, you can't set this property in his own setter, you should have some field and set it in setter:

    public string someValue = System.Configuration.ConfigurationSettings.AppSettings["key1"];    
    
    public string Property1
    {
        get
        {
            return someValue;
        }
        set
        {
            someValue = value;
        }
    }
    

    Or you can use auto-property:

    C# 6:

    public string Property1 {get;set;} = System.Configuration.ConfigurationSettings.AppSettings["key1"]; 
    

    Or lower than C# 6 - you should declare you property and initialize it in contructor or method:

    public string Property1 {get;set;} 
    
    public void ConstructorOrMethod()
    {
        Property1 = System.Configuration.ConfigurationSettings.AppSettings["key1"]; 
    }