#Net5 – C#9 “records” and “deconstruction” super cool feature 🆒🆒🆒

Buy Me A Coffee

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:

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.