Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Constructor without new C#

Tags:

c#

constructor

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 in separate.

like image 765
Fausto Sanchez Avatar asked Dec 11 '22 17:12

Fausto Sanchez


2 Answers

Those are so called factory methods and technically are static methods on the Class (person) that are then called on the class (Person.Create).

Technically they internally create the Person with new - but it can happen with a PRIVATE CONSTRUCTOR.

like image 53
TomTom Avatar answered Dec 30 '22 04:12

TomTom


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

class Person {
  public Person(string name) {
    //Constructor logic
  }
  public static Person CreatePerson() {
    return new Person(string.Empty);
  }
}
like image 34
Aidy J Avatar answered Dec 30 '22 04:12

Aidy J