Alexander Zeitler

Deconstructing a C# record with properties

Published on Tuesday, June 7, 2022

Photo by Florian Klauer on Unsplash

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.

What are your thoughts about
"Deconstructing a C# record with properties"?
Drop me a line - I'm looking forward to your feedback!
Please be aware that I'm no longer active on social media. I'm just cross posting things over there (it's a bot).
Imprint | Privacy