Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why I get this "infinite loop" on Class properties?

This is my property on my code :

public KPage Padre
{
    get
    {
        if (k_oPagina.father != null)
        {
            this.Padre = new KPage((int)k_oPagina.father);
        }
        else
        {
            this.Padre = null;
        }

        return this.Padre;
    }
    set { }
}

but it says :

An unhandled exception of type 'System.StackOverflowException' occurred in App_Code.rhj3qeaw.dll

Why? How can I fix it?

EDIT

After correct the code, this is my actual code :

private KPage PadreInterno;
public KPage Padre
{
    get
    {
        if (PadreInterno == null)
        {
            if (paginaDB.father != null)
            {
                PadreInterno = new KPage((int)paginaDB.father);
            }
            else
            {
                PadreInterno= null;
            }
        }

        return PadreInterno;
    }
}

What do you think about?

like image 482
markzzz Avatar asked Nov 30 '25 05:11

markzzz


1 Answers

The property is calling itself... usually properties call underlying fields:

   public KPage Padre
   {
       get
       {
           if (k_oPagina.father != null)
           {
               _padre = new KPage((int)k_oPagina.father);
           }
           else
           {
               _padre = null;
           }

           return _padre;
       }
       set { }
   }

   private KPage _padre;

Your old code was recursively calling the get of the Padre property, hence the exception.

If your code only "gets" and doesn't need to store the value, you could also get rid of the backing field entirely:

   public KPage Padre
   {
       get
       {
           return k_oPagina.father != null
              ? new KPage((int)k_oPagina.father)
              : (KPage)null;
       }
   }

That said, I'd put this in a method.

This is also the same issue as the one you asked a couple of days ago:

An unhandled exception of type 'System.StackOverflowException' occurred

like image 67
Adam Houldsworth Avatar answered Dec 01 '25 19:12

Adam Houldsworth



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!