1

I was wondering if it's valid to initialize an instance of a class within the same class? For example:

public class Person()
{ 
   string name;
   string age;
   public Person getPerson()
   { 
       Person p1=new Person();
       //some logic here
       return p1
    }
}

I ended up doing that for a part of my code at work and thus wanted to know if there are any potential problems with doing something like this.

  • When the instance returned by getPerson is not influenced by the Person instance you call it on, the function should be declared and called static. – Philipp Jul 31 '13 at 14:42
6

Yes, it is valid.

That's called a factory method.

The Calendar class, for example has a getInstance() method.

That's also useful when implementing the Singleton pattern.

Here you have a SO question about when to use a factory method.

1

Yes. Often done when you need to build large, dynamic, self-maintaining structures like Trees:

class Tree {

  public IComparable Value;
  private Tree Left;
  private Tree Right;

  public Add (IComparable value) {
    if (this.Value == null) {
      this.Value = value;

      // RIGHT HERE!
      this.Left = new Tree();
      this.Right = new Tree();

    } else {
      if (value > this.Value) {
        this.Right.Add(value);
      } else {
        this.Left.Add(value);
      }
    }
  } // Add()

} // class Tree

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.