9

Why this? This is my code :

public class KPage
{
    public KPage()
    {
       this.Titolo = "example";
    }

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

I set data by the constructor. So, I'd like to do somethings like

KPage page = new KPage();
Response.Write(page.Titolo);

but I get that error on :

set { Titolo = value; }
2
  • 1
    possible duplicate of Overloading Getter and Setter Causes StackOverflow in C# or stackoverflow.com/questions/5676430/… Commented Apr 4, 2012 at 20:01
  • 8
    The Titolo getter uses the Titolo property. Whose getter uses the Titolo property. Whose getter uses the Titolo property. Whose getter uses the Titolo property. Whose getter uses the Titolo property. Whose getter uses the Titolo property. Whose getter uses the Titolo property... Kaboom. Commented Apr 4, 2012 at 20:02

3 Answers 3

39

You have an infinite loop here:

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

The moment you refer to Titolo in your code, the getter or setter call the getter which calls the getter which calls the getter which calls the getter which calls the getter... Bam - StackOverflowException.

Either use a backing field or use auto implemented properties:

public string Titolo
{
    get;
    set;
}

Or:

private string titolo;
public string Titolo
{
    get { return titolo; }
    set { titolo = value; }
}
Sign up to request clarification or add additional context in comments.

Comments

3

You have a self-referential setter. You probably meant to use auto-properties:

public string Titolo
{
    get;
    set;
}

Comments

2

Change to

public class KPage
{
    public KPage()
    {
       this.Titolo = "example";
    }

    public string Titolo
    {
        get;
        set;
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.