When should i use Private constractor with factory method?

here included example
c#
public class Student
{

private string name;
private Student(string name)
{
this.name = name;
}

public static Student CreateObject(string name)
{
return new Student(name);
}

public string Name
{
get { return name; }
}


}
c#
public class Student
{

private string name;
private Student(string name)
{
this.name = name;
}

public static Student CreateObject(string name)
{
return new Student(name);
}

public string Name
{
get { return name; }
}


}
7 Replies
Angius
Angius6mo ago
Most often, when you need some async work done on construction For example,
public class Classroom
{
public List<Student> Students { get; private set; }

private Student(List<Student> students)
{
Students = students;
}

public static async Task<Classroom> CreateInstance()
{
var data = await File.ReadAllTextAsync("students.json");
var students = JsonSerializer.Deserialize<List<Student>>(data);
return new Classroom(students);
}
}
public class Classroom
{
public List<Student> Students { get; private set; }

private Student(List<Student> students)
{
Students = students;
}

public static async Task<Classroom> CreateInstance()
{
var data = await File.ReadAllTextAsync("students.json");
var students = JsonSerializer.Deserialize<List<Student>>(data);
return new Classroom(students);
}
}
Other than that, it's done when some heavier work needs to be done before the instance is complete. Constructors, ideally, should be very simple and lightweight So it makes sense, ideologically, to have heavy work done in a factory
steven preadly
steven preadlyOP6mo ago
this is an advanced topic for me now as a biggner
Angius
Angius6mo ago
Yes, static factories are not something you would use often It's not something a beginner should be concerned with much
steven preadly
steven preadlyOP6mo ago
but its ok to just have the infrmation correct
Angius
Angius6mo ago
Sure
steven preadly
steven preadlyOP6mo ago
ok thank you
SleepWellPupper
SleepWellPupper6mo ago
2cents: Constructors should be - simple - fast [citation needed] My rule of thumb is that if the initialization of objects is rather complicated / async (as mentioned) / or requires stuff that is transformed into what the object actually needs, then I use factory methods.
Want results from more Discord servers?
Add your server