An unhandled exception of type 'System.StackOverflowException' occurred

Go To StackoverFlow.com

8

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; }
2012-04-04 19:57
by markzzz
possible duplicate of Overloading Getter and Setter Causes StackOverflow in C# or http://stackoverflow.com/questions/5676430/stackoverflowexception-was-unhandle - user7116 2012-04-04 20:01
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 - Hans Passant 2012-04-04 20:02


37

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; }
}
2012-04-04 19:59
by Oded


3

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

public string Titolo
{
    get;
    set;
}
2012-04-04 19:59
by user7116


2

Change to

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

    public string Titolo
    {
        get;
        set;
    }
}
2012-04-04 19:59
by Albin Sunnanbo
Ads