From the course: Advanced C#: Functional Programming Patterns

Unlock this course with a free trial

Join today to access over 22,600 courses taught by industry experts.

Use factory method to create instance

Use factory method to create instance - C# Tutorial

From the course: Advanced C#: Functional Programming Patterns

Use factory method to create instance

- Here's a classic problem you'll find in immutable types or any type that has their property set through a constructor, it's called Constructor explosion. And it comes from when you have constructors that are used to set the properties and you make a lot of those properties optional. So let's say I've got four properties, net red, green, blue, and alpha, which is the transparency level. And none of these are required. So I can have a constructor that takes zero arguments, or I can have a constructor that only takes red or one that only takes blue or one that takes alpha and green or red and blue, you get the idea. So I could go from, I might need 15 constructors for four properties or 31 constructors for five properties so that's the explosion. Then the solution for this is to write a factory method or a builder method, that builds it with these optionals. You can do this with constructors, but this is a more elegant approach.…

Contents