
Hi !
I’m still learning about C#9, and there is a lot to learn about records. And, between all this information, I Just learn a super cool feature related to records: deconstruction.
Let’s start with a simple record definition for a pet. This one includes pet’s name and pet’s age:
public record Pet { public string Name { get; init; } public int Age { get; init; } public Pet(string name, int age) => (Name, Age) = (name, age); }
This is fine, init only properties (cool feature!) and we can access the values as usual.
static void Main(string[] args) { var pet = new Pet("Goku", 2); // get pet info, standard way var gokuName = pet.Name; var gokuAge = pet.Age; }
So far, so good. However, if you like clean code, we can improve this a little using some new features in C#9. So, let’s start with much simpler record definition.
public record NewPet(string Name, int Age);
And we can access the pet properties using deconstruction (new term for me!)
// get pet info, C#9 deconstruction var newPet = new NewPet("Goku", 2); var (gokuName, gokuAge) = newPet;
I like this new one 👆 too ! I’ll always like features that improves readability and saves us a lot of extra code.
Happy coding!
Greetings
El Bruno
References
¿Con ganas de ponerte al día?
En Lemoncode te ofrecemos formación online impartida por profesionales que se baten el cobre en consultoría:
- Si tienes ganas de ponerte al día con Front End (ES6, Typescript, React, Angular, Vuejs…) te recomendamos nuestros Máster Front End: https://lemoncode.net/master-frontend#inicio-banner
- Si te quieres poner al día en Backend (stacks .net y nodejs), te aconsejamos nuestro Bootcamp Backend: https://lemoncode.net/bootcamp-backend#bootcamp-backend/banner
- Y si tienes ganas de meterte con Docker, Kubernetes, CI/CD…, tenemos nuestro Bootcamp Devops: https://lemoncode.net/bootcamp-devops#bootcamp-devops/inicio