1

Can I define constructor like this? Additional question: Can I call constructor of the class in itself constructor?

class SubArray
{
    List<int> array;
    string parent;
    string name;
    SubArray child;

    public SubArray(SubArray child, string name)
    {
        this.child = child;
        List<int> array = new List<int>();
        this.name = name;
    }
}
11
  • In the code sample you provided you are NOT calling the constructor of SubArray from within the constructor of SubArray. Commented Feb 13, 2013 at 13:15
  • I know that. It was additional question Commented Feb 13, 2013 at 13:16
  • And why would you want to do that? Commented Feb 13, 2013 at 13:17
  • have you tried? what was the result? Also what are you trying to do, add new subarray objects and set their properties or replace the existing properties in one object? Commented Feb 13, 2013 at 13:18
  • 1
    At the very least delegate the recursive part to a different method call. Constructors should not perform long running operations. Commented Feb 13, 2013 at 13:28

2 Answers 2

12

There is no limit on that, but like any recursion - it needs a stopping condition. otherwise it will cause a stack overflow (PUN intended :)).

Sign up to request clarification or add additional context in comments.

1 Comment

Extra kudos for the pun there. :)
4

I guess you could do something like this and there is no....apparent problem:

public SubArray(SubArray child, string name)
{
    this.child = child;
    this.array = new List<int>();
    this.name = name;

    if (child != null && child.child != null)
    {
        this.child.child = new SubArray(child.child,name);
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.