Why am I getting this "infinite loop" in the class properties?

This is my property in 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 he says:

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

Why? How can I fix this?

EDIT

After correct 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?

+3


source to share


1 answer


A property calls itself ... typically the following fields call properties:

   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 get

properties Padre

, hence the exception.

If your code "gets" and doesn't need to store the value, you can 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;
       }
   }

      

However, I would put this in a method.

This is also the same problem you asked a couple of days ago:

fooobar.com/questions/773272 / ...

+7


source







All Articles