C# 7.0 – Deconstruct in a C# Class

In my blog, I explained how a Tuple could be consumed via deconstruction. Its important to know that this concept is not specific to Tuples. In today’s post I will show how that concept could be applied to a regular class.  Let’s say you have following Employee class.

class Employee
{
  public string FirstName { get; set; }
  public string LastName { get; set; }
  public string MiddleName { get; set; }
}

You can add a Deconstruct method to this class that accepts out parameters that could be initialised in the method for consumption by deconstruction. So let’s add a Deconstruct method as follows.

class Employee
{
  public string FirstName { get; set; }
  public string LastName { get; set; }
  public string MiddleName { get; set; }

  public void Deconstruct(out string firstName, out string lastName)
  {
     firstName = this.FirstName;
     lastName = this.LastName;
  }
}

Now this class can be consumed as follows using deconstruct syntax.

static void Main(string[] args)
{
    var employee = new Employee() { FirstName = "John", LastName = "Doe", MiddleName = "Sue" };
 
    (string firstName, string lastName) = employee;
    Console.WriteLine($"First Name = {firstName} Last Name = {lastName}");
}

Output of this will be as follows.

Capture

Your class can expose more then one Deconstruct method with varying number of parameters, so that it can be consumed appropriately.  Code below shows same Employee class with two Deconstruct methods.

class Employee
{
 public string FirstName { get; set; }
 public string LastName { get; set; }
 public string MiddleName { get; set; }

 public void Deconstruct(out string firstName, out string lastName)
 {
    firstName = this.FirstName;
    lastName = this.LastName;
 }
 public void Deconstruct(out string firstName, out string lastName, out string middleName)
 {
    firstName = this.FirstName;
    lastName = this.LastName;
    middleName = this.MiddleName;
 }
}

Now you can consume the object using deconstruction in similar manner as shown below.

static void Main(string[] args)
{
  var employee = new Employee() { FirstName = "John", LastName = "Doe", MiddleName = "Sue" };
 
  (string firstName, string lastName, string middleName) = employee;
  Console.WriteLine($"First Name = {firstName} Last Name = {lastName} Middle Name = {middleName}");
}

The output now contains the Middle Name as well.

Capture

Until next, happy debugging.

 

Advertisements
This entry was posted in Uncategorized. Bookmark the permalink.

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s