From the course: Advanced C#: Functional Programming Patterns
Unlock this course with a free trial
Join today to access over 24,500 courses taught by industry experts.
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 to 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 now: 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 properties or 31 constructors for five properties. So that's the explosion. Now the solution for this is to write a factory method or a builder method that builds it with these options. You can do this with constructors, but this is a more elegant approach. So let's see what we've done. So I've added the fourth property…
Contents
-
-
-
-
-
-
-
Principles of immutable types2m 10s
-
(Locked)
Simple immutable example1m 51s
-
(Locked)
More principles2m 49s
-
(Locked)
Read-only properties2m 44s
-
(Locked)
Instance method in immutable type3m 10s
-
(Locked)
Use helper methods to create new instance2m 23s
-
(Locked)
Use factory method to create instance3m 30s
-
-
-
-
-
-
-