Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

An unhandled exception of type 'System.StackOverflowException' occurred

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; }
like image 756
markzzz Avatar asked Apr 04 '12 19:04

markzzz


People also ask

What is System StackOverflowException?

StackOverflowException is thrown for execution stack overflow errors, typically in case of a very deep or unbounded recursion. So make sure your code doesn't have an infinite loop or infinite recursion. StackOverflowException uses the HRESULT COR_E_STACKOVERFLOW, which has the value 0x800703E9.

Can we handle StackOverflowException?

Since the StackOverflowException cannot be caught even though we can make use of try blocks of code and catch blocks of code, by knowing the depth of the stack which can be obtained by using the debugger, we can create our own exceptions.


3 Answers

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; }
}
like image 110
Oded Avatar answered Sep 28 '22 00:09

Oded


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

public string Titolo
{
    get;
    set;
}
like image 45
user7116 Avatar answered Sep 28 '22 00:09

user7116


Change to

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

    public string Titolo
    {
        get;
        set;
    }
}
like image 38
Albin Sunnanbo Avatar answered Sep 28 '22 01:09

Albin Sunnanbo