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
Angius2mo 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 preadly2mo ago
this is an advanced topic for me now as a biggner
Angius
Angius2mo 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 preadly2mo ago
but its ok to just have the infrmation correct
Angius
Angius2mo ago
Sure
steven preadly
steven preadly2mo ago
ok thank you
SleepWellPupper
SleepWellPupper2mo 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.