Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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.

share|improve this question
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

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.

share|improve this answer
Should be noted that for a factory, getPerson() should be static. – Steven Burnap Jul 31 '13 at 3:34
If it is not static, and it copies data from the current instance to the new instance, it is a clone method. – rwong Jul 31 '13 at 4:05

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) {
      } else {
  } // Add()

} // class Tree
share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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