Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The requested operation caused a stack overflow [closed]

Tags:

c#

I am trying to create a derived class and the error pops up. Not quite sure how it comes out. Please help!

Base class:

public class Command : identifiableobject
{
    LookCommand l = new LookCommand();

    public virtual string Execute (Player p, string[] text)
    {
        return "";

    public Command (string[] ids) : base(ids)
    {
    }
}

Derived class

public class LookCommand : Command
{
    public LookCommand () : base (new string[] {"look"})
        {
        }
}

The error pops up when I try to create a new Command Object. Any ideas why?

like image 425
Tree Nguyen Avatar asked Mar 16 '26 12:03

Tree Nguyen


1 Answers

This is the problem:

public class Command : identifiableobject
{
    LookCommand l = new LookCommand();

    ...

That means that in order to construct a Command, you need to construct a new LookCommand. But a LookCommand is a Command, so constructing one LookCommand requires constructing another one, which constructs another one, etc.

We don't know what you're trying to achieve with the l variable here, but that's what's causing the Either you need to get rid of that variable, or don't initialize it in that way, or make LookCommand not derive from Command.

like image 80
Jon Skeet Avatar answered Mar 19 '26 00:03

Jon Skeet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!