Static Factory Methods vs Constructors In C#

// Using the constructor
SqlConnection myConnection = new SqlConnection(connectionString);

// Using a static factory method
IDbConnection myConnection = SqlConnection.FromConnectionString(connectionString);

Pros of Static Factory Methods

No need to return a new instance

You can use method references

// Static factory method - the method group can be passed in directly as a function reference
var bars = myFoo
.Select(bar.FromFoo)

// Constructors - you have to pass in a lambda that constructs the instance via new.
var bars = myFoo
.Select(f => new Bar(f));

You can name ‘em

// With constructors
var color = new Color(25, 25, 5, 80);
var color = new Color(100, 150, 50);

// With static factory methods
var color = Color.FromCMYK(25, 25, 5, 80);
var color = Color.FromRGB(100, 150, 50);

Factory Methods can return a different class

// This could create an IpV4IpAddress that implements IIpAddress 
IIpAddress ipv4Address = IpAddress.FromString("127.0.0.1");

// This could create an IpV6IpAddress that implements IIpAddress
IIpAddress ipv6Address = IpAddress.FromString("2001:0db8:0a0b:12f0:0000:0000:0000:0001")

There Are Things You Shouldn’t Do In Constructors

Cons of Static Factory Methods

There Are Things You Shouldn’t Do In Constructors

There’s more code

They’re harder to find

  • You should always create one constructor that maps 1:1 to the fields internally in the class.
  • If you need to do anything fancy to create the object, such as IO, or you’re interested in caching objects and reusing them, use a static factory method.
  • If you need API stability, such as for library development, hide that constructor and use a static factory method because of the implementation flexibility it gives you.
  • If you have multiple different ways to create your class, create static factory methods and use those, because of the descriptiveness they give you.

--

--

--

Software Developer at SCADA Minds

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Technical Debt ..A hidden bug in your Organisation

Sorting Algorithms — Time Table

A story of leaking uninitialized memory from Fastly

Magical Performance Improvements with Redis Caching in Django

YouTube Video | Mobile-First Website with CSS Grid -2

AuroraFS

Setup Node server on AWS ec2 from scratch

My Journey with WordPress

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Gustav Wengel

Gustav Wengel

Software Developer at SCADA Minds

More from Medium

Happy Birthday .NET — 20 Years of .NET Framework

Build a simple Chat Room using Mediator Pattern (C#)

C# code quality tooling with Roslyn, Resharper and NDepend

C# Value Types and Reference Types

Into Image