33
44Let's learn more about this process by looking at the following code examples.
55
6- ## Example: Deconstruct a tuple
6+ ## Example: Deconstruction of a tuple object
77
88``` csharp
99// declare a tuple
@@ -19,7 +19,7 @@ Console.WriteLine($"Price: {price}");
1919
2020```
2121
22- ## Example: Deconstruct a dictionary
22+ ## Example: Deconstruction of a dictionary object
2323
2424``` csharp
2525// declare a dictionary object
@@ -34,7 +34,7 @@ foreach((string k, string v) in books)
3434 Console .WriteLine ($" \" {k }\" written by {v }" );
3535}
3636```
37- ## Example: Deconstruct a class
37+ ## Example: Deconstruction of a class
3838We need to implement the ` Deconstruct ` method. We can have multiple implementation of this method by overloading.
3939
4040``` csharp
@@ -82,7 +82,7 @@ var (myBookTitle, myBookAuthor) = mybook;
8282Console .WriteLine ($" \" {myBookTitle }\" by {myBookAuthor }" );
8383```
8484
85- ## Example: Deconstruct a record
85+ ## Example: Deconstruction of a record
8686
8787``` csharp
8888// define a record called "Person" with the props
@@ -94,6 +94,24 @@ var person = new Person("Jon", "Doe");
9494var (firstName , lastName ) = person ;
9595Console .WriteLine ($" My name is {firstName } {lastName }" );
9696```
97+
98+ ## Example: Deconstruction using extension method
99+
100+ ``` csharp
101+ // implemeted an extension method
102+ public static void Deconstruct (this DateTimeOffset date , out int day , out int month , out int year ) =>
103+ (day , month , year ) = (date .Day , date .Month , date .Year );
104+ ```
105+
106+ ``` csharp
107+ // now instantitate DateTimeOffset
108+ var date = new DateTimeOffset (2022 , 9 , 17 , 0 , 0 , 0 , 0 , TimeSpan .Zero );
109+
110+ // deconstruct DateTimeOffset objcet
111+ (int day , int month , int year ) = date ;
112+ Console .WriteLine ($" I wrote this example on: {month }/{day }/{year }" );
113+ ```
114+
97115---
98116## Links:
99117- [ Deconstructing tuples and other types] ( https://learn.microsoft.com/en-us/dotnet/csharp/fundamentals/functional/deconstruct )
0 commit comments