#Net5 – C#9 “records”, “with” and “this”, a super cool mix 🆒🆒🆒

Buy Me A Coffee

Hi !

Our next podcast episode is focused on .Net 5. We had an amazing chat around a lot of features, and of course, C# 9 was part of the conversation.

I got this amazing post [C# 9.0: Records – Work With Immutable Data Classes] from Tomas Huber, in my reading notes and working with records is something that I wanted to test.

In a few words, a record is an immutable class. Which is super cool, because it allows some cool operations for mapping, reflection and more. Again, please read Tomas post.

On of the features of records is that once, you define a record with a constructor, there is no default constructor anymore. Let’s start with a simple person record with 3 properties for Name, Age and Married status (as boolean)

public record PersonRecord(string Name, int Age, bool Married)
{
    public override string ToString() => 
        $"Name: {Name} - Age: {Age} - Married: {Married}";
}

Losing the default constructor can be a challenge if we want to copy a record. However we can take advantage of the with expression and create new objects that uses the protected copy constructor. Let’s take a look at the same person object with a CopyUsingMarriedTrue() function that, creates a new object with the same properties changing the value of the Married property.

public record PersonRecord(string Name, int Age, bool Married = false)
{
    public Guid Id { get; init; } = Guid.NewGuid();
    public override string ToString() => 
        $"Name: {Name} - Age: {Age} - Married: {Married} - Guid: {Id}";

    public PersonRecord CopyUsingMarriedTrue() => this with { Married = true };
}

Now it’s time for a full Console test, where I create a couple of persons and check the values of the person. Important, I added a Guid Id property to test the copy and constructor behavior.

  • Lines 14 to 18, I created a Bruno person with Married as True, and I created a BrunoMarried to check the new created object.
  • Lines 20 to 25, I created a Valentino person with Married as False and I created a ValentinoMarried to check the new created object.
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Security.Cryptography.X509Certificates;
namespace ConsoleApp3
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("start");
var bruno = new PersonRecord("Bruno", 40, true);
Console.WriteLine($"{bruno.ToString()}");
Console.WriteLine($"Bruno Is Married created");
var brunoMarried = bruno.CopyUsingMarriedTrue();
Console.WriteLine($"{brunoMarried }");
Console.WriteLine($"———————————–");
var valentino = new PersonRecord("Valentino", 13, false);
Console.WriteLine($"{valentino.ToString()}");
Console.WriteLine($"Valentino Is Married created");
var valentinoMarried = valentino.CopyUsingMarriedTrue();
Console.WriteLine($"{valentinoMarried}");
}
}
public record PersonRecord(string Name, int Age, bool Married = false)
{
public Guid Id { get; init; } = Guid.NewGuid();
public override string ToString() => $"Name: {Name} – Age: {Age} – Married: {Married} – Guid: {Id}";
public PersonRecord CopyUsingMarriedTrue() => this with { Married = true };
}
}

The output is an awesome surprise. I mean, my code always surprise me, however using this feature is an awesome surprise !

start
Name: Bruno - Age: 40 - Married: True - Guid: 82e60022-0fb2-456d-89c0-ab88bef5aff6
Bruno Is Married created
Name: Bruno - Age: 40 - Married: True - Guid: 82e60022-0fb2-456d-89c0-ab88bef5aff6
-----------------------------------
Name: Valentino - Age: 13 - Married: False - Guid: 7acca9e2-f461-4fc9-8e29-06f6f0ffb6c6
Valentino Is Married created
Name: Valentino - Age: 13 - Married: True - Guid: 7acca9e2-f461-4fc9-8e29-06f6f0ffb6c6
csharp 9 with and records

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:

One thought on “#Net5 – C#9 “records”, “with” and “this”, a super cool mix 🆒🆒🆒

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.