Constructor without new C #

I wonder how I could write this type of constructors:

Person p = Person.CreateWithName("pedro");
Person p1 = Person.CreateEmpty();

And having the code of each constructor separately.

+4
source share
3 answers

You can implement it as follows:

  public class Person {
    // Private (or protected) Constructor to ensure using factory methods
    private Person(String name) { 
      if (null == name)
        name = "SomeDefaultValue";

      //TODO: put relevant code here
    }

    // Factory method, please notice "static"
    public static Person CreateWithName(String name) {
      return new Person(name); 
    }

    // Factory method, please notice "static"
    public static Person CreateEmpty() {
      return new Person(null); 
    } 
  }
+2
source

These are the so-called factory methods and are technically static methods of a class (person), which are then called in the class (Person.Create).

Technically, they internally create a Human with a new one - but this can happen with a PRIVATE CONSTRUCTOR.

+6
source

You just create a static method inside this class, i.e.

class Person {
  public Person(string name) {
    //Constructor logic
  }
  public static Person CreatePerson() {
    return new Person(string.Empty);
  }
}
+5
source

All Articles