C# › Design Patterns in C#

How does the Factory Method pattern work in C#, and what problem does it solve?

Beginner

Answer

A Factory Method encapsulates object-creation logic behind a method (often on a base class or interface) that subclasses or implementations override to decide WHICH concrete type to instantiate — this decouples the calling code from needing to know or reference specific concrete classes directly.
public abstract class ShapeFactory {
  public abstract IShape CreateShape();
}
public class CircleFactory : ShapeFactory {
  public override IShape CreateShape() => new Circle();
}
Real-world example Building a document-processing system where different factories create different parser implementations depending on file type.

Common follow-ups: How does the Factory Method pattern differ from the more general Abstract Factory pattern?