Medium csharp

OOP — Static factory method

Problem

Use static Employee.Create factory instead of public constructor.

Hints
  • Private ctor + public static Create

Your practice code

Ready — edit the code above and click Run.

Solution

using System;

class Employee {
    public string Name { get; private set; }
    private Employee(string name) => Name = name;
    public static Employee Create(string name) => new Employee(name);
}
class Program {
    static void Main() {
        var e = Employee.Create("Sara");
        Console.WriteLine(e.Name);
    }
}

Try solving on your own first, then reveal the official answer.

Explanation

Factory pattern controls object creation—common in enterprise C#.

Toolliyo Assistant
Ask about tutorials, ebooks, training, pricing, mentor services, and support. I use public site content only—not admin or internal tools.

care@toolliyo.com

Need callback? Share your details