Search code examples
c#interfacestack-overflow

How to solve StackOverflowException


I try to write this class:

public class ModelManager
{
    public OmniacareHomeProductionEntities _db;

    public CategoriaManager categoriaManager 
    { 
        get { return categoriaManager; }
        set 
        {
            if (categoriaManager == null)
            {
            categoriaManager = new CategoriaManagerImpl();
            }
        }
    }

    private static readonly log4net.ILog log = log4net.LogManager.GetLogger(typeof(ModelManager));
    public ModelManager()
    {
        _db = new OmniacareHomeProductionEntities();
    }
}

CategoriaManager is an Interface and CategoriaManagerImpl is a class that implements CategoriaManager.

I use ModelManager class in this mode:

ModelManager modelManager = new ModelManager();
modelManager.categoriaManager.saveLocalCategory(category, true);

so when I try to run this code, I have a StackOverflowError at this line

get 
{
    return categoriaManager;
}

Where is my error? Can you help me?


Solution

  • Your problem is clearly here

      public CategoriaManager categoriaManager 
        { 
            get 
            {
                return categoriaManager;
            }
            set 
            {
                if (categoriaManager == null)
                {
                    categoriaManager = new CategoriaManagerImpl(); //HERE !!!!!!!!!
                }
            }
        }
    

    the name of the member is the same of the property, change it like this, for example:

        public CategoriaManager CatManager //NAME OF HE PROPERTY ISCHANGED !!!!
        { 
            get 
            {
                return categoriaManager;
            }
            set 
            {
                if (categoriaManager == null)
                {
                    categoriaManager = new CategoriaManagerImpl();
                }
            }
        }
    

    General guideline:

    • for properties use names starting from upper case
    • for fields use names starting from low case

    So your code would lool like this:

    ModelManager modelManager = new ModelManager();
    modelManager.CatManager.saveLocalCategory(category, true);