
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