Browse Source

Builder example

Piotr Czajkowski 6 months ago
parent
commit
864c2c308f
1 changed files with 31 additions and 0 deletions
  1. 31 0
      20220125/builder.cs

+ 31 - 0
20220125/builder.cs

@@ -0,0 +1,31 @@
+using System;
+
+namespace BuilderPatternWithRecords
+{
+    record Address(string Line1, string Line2, string ZipCode,
+    string City, string Country);
+
+    record AddressBuilder(
+    string Line1 = "Line 1", string Line2 = "Line 2", string ZipCode = "00-123",
+    string City = "Lorem City", string Country = "Poland")
+    {
+        public Address Build() => new Address(Line1, Line2, ZipCode, City, Country);
+    }
+
+    class Program
+    {
+        static void Main(string[] args)
+        {
+            var address1 = new AddressBuilder().Build();
+            Console.WriteLine(address1);
+
+            var address2 = new AddressBuilder { ZipCode = "lorem" }.Build();
+            Console.WriteLine(address2);
+
+            var builder = new AddressBuilder { City = "Warsaw" };
+            var warsawA = (builder with { Line1 = "Z" }).Build();
+            var warsawB = (builder with { Line1 = "A" }).Build();
+            Console.WriteLine($"{warsawA}, {warsawB}");
+        }
+    }
+}