5

Deconstructing a C# record with properties

 1 year ago
source link: https://alexanderzeitler.com/articles/deconstructing-a-csharp-record-with-properties/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Alexander Zeitler

Deconstructing a C# record with properties

Published on Monday, June 6, 2022

Photo by Florian Klauer on Unsplash

florian-klauer--K6JMRMj4x4-unsplash.jpg

Today I tried to deconstruct a C# record with properties and I failed.

First, how do you deconstruct a record with positional parameters?

It's as easy like this:

public record Person(
string FirstName,
string LastName
);

var janeDoe = new Person("Jane", "Doe");
var (lastName, firstName) = janeDoe;

That's it.

My naïve approach (the record is simplyfied for brevity) to deconstruct a record with properties was like this:

public record Person()
{
public string Firstname { get; init; }
public string Lastname { get; init; }
}

Next, I created an instance:

var janeDoe = new Person() { Firstname = "Jane", Lastname = "Doe" };

Now I tried to deconstruct it like I would do with the first sample:

var (lastName, firstName) = janeDoe;

And I got this compiler error:

$ No 'Deconstruct' method with 2 out parameters found for type 'Person'

After reading this error message several times, I got it: the compiler is expecting a method name Deconstruct like this on my Person record type:

public record Person()
{
public string Firstname { get; init; }
public string Lastname { get; init; }
public void Deconstruct(
out string firstName,
out string lastName
) => (firstName, lastName) = (Firstname, Lastname);
}

Deconstruction now works as expected:

var (lastName, firstName) = janeDoe;

The reason for this issue is quite simple: The C# compiler auto-generates the Deconstruct method when you have a record type with positional parameters but not for record types with properties.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK