Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

StackOverflowException on Getter C#

Tags:

c#

uwp

I am getting a StackOverflowException on the get; of a property in an abstract class.

public abstract class SenseHatSnake
    {

        private readonly ManualResetEventSlim _waitEvent = new ManualResetEventSlim(false);

        protected SenseHatSnake(ISenseHat senseHat)
        {
            SenseHat = senseHat;
        }

        protected static ISenseHat SenseHat { get; set; } // This Line

        public virtual void Run()
        {
            throw new NotImplementedException();
        }

        protected void Sleep(TimeSpan duration)
        {
            _waitEvent.Wait(duration);
        }

    }

I am setting and getting it here:

public class SnakeGame : SenseHatSnake
{
    private readonly int _gameSpeed = 1000;
    private static Timer _updatePositionTimer;
    private bool _gameOver = false;

    public readonly Movement Movement = new Movement(SenseHat);
    public readonly Food Food = new Food(SenseHat);
    public readonly Body Body = new Body(SenseHat);
    public readonly Display Display = new Display(SenseHat);
    public readonly Draw Draw = new Draw(SenseHat);

    public SnakeGame(ISenseHat senseHat)
        : base(senseHat)
    {
    }
    //More code
}

One of those classes look like this:

public class Movement : SnakeGame
{

    public Movement(ISenseHat senseHat)
        : base(senseHat)
    {
    }
    //More code
}

To my knowledge a StackOverflowException means I somewhere have an an infinite loop or infinite recursion, but I honestly don't know where, nor do I know how to solve it.

like image 526
Luuk Wuijster Avatar asked Nov 30 '22 21:11

Luuk Wuijster


1 Answers

This line in SnakeGame causes a recursion

public readonly Movement Movement = new Movement(SenseHat);

Since Movement is inherited from SnakeGame, its constructor will initialize SnakeGame, calling the line above again to initialize its own Movement field. That results into recursion.

like image 186
Bagdan Gilevich Avatar answered Dec 09 '22 19:12

Bagdan Gilevich