skilldwill
skilldwill

Reputation: 31

Initializing subclass object in class - StackOverflowException

I stripped my code to the parts that cause the problem. The code jumps back and forth lines 5 and 9 here, causing stackoverflowexception.

How could I do this differently? I need the Platform instance inside Game class to use in functions.

namespace Games
{
    public class Game
    {
        private Platform platform = new Platform();
    }
    class Platform : Game
    {
        private bool[] squares = new bool[9];
    }
}

Upvotes: 3

Views: 53

Answers (1)

Crowcoder
Crowcoder

Reputation: 11514

When a Game instance is created it creates an instance of Platform which will invoke the base class constructor which creates an instance of Platform which will invoke the base class constructor which will...

See where this is leading?

You should use Platform where you are trying to use Game. Many would argue not to use inheritence at all. Consider composition which in your case might mean Game has a property of type Platform but Platform does not inherit from Game.

Upvotes: 1

Related Questions