Learned a cool little trick a while back from Khalid. As a developer, you will often run into scenarios that require you to get a subset of all fields from a model. There are many ways to achieve this task, returning the type and then grabbing each property, for example, take the following User type.
|
|
If you want to obtain the name and id property you can take the following approach.
|
|
Simple enough, I’m sure every developer at some point in their career has written code similar to the example above. The trick I learned makes this even simpler. It involves declaring deconstructing methods to extract information from types. The same example as above can now be written as.
|
|
You can declare multiple deconstructors per type, simply change the signature, so in the example above if I wanted to get the Id and date of birth instead of the name and the date of birth, I would need to add the following code to the User type.
|
|
If you prefer not to pollute your types with many deconstruct methods, you have the option to declare them in an extension class. For example, in the case of the User type, I can declare a new class UserExtensions.
|
|
and you use the same syntax to invoke it.
|
|
This is super useful when you need to extract various values and don’t want to use a Tuple or declare another class.