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

.net, c#, properties, stack-overflow

Solution

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

Problem

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?

Original source

Related problems