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

// Static factory method - the method group can be passed in directly as a function reference
var bars = myFoo

// Constructors - you have to pass in a lambda that constructs the instance via new.
var bars = myFoo
.Select(f => new Bar(f));
// 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);
// This could create an IpV4IpAddress that implements IIpAddress 
IIpAddress ipv4Address = IpAddress.FromString("");

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

Cons of Static Factory Methods



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