Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to overload deconstructors in C# 7.0?

In C# 7.0 I can declare the following deconstructors for my class:

public class Customer
{
    public string FirstName { get; }
    public string LastName { get; }
    public string Email { get; }

    public Customer(string firstName, string lastName)
    {
        FirstName = firstName;
        LastName = lastName;
    }

    public void Deconstructor(out string firstName, out string lastName, out string company)
    {
        firstName = FirstName;
        lastName = LastName;
        company = "Nop-Templates";
    }

    public void Deconstructor(out string firstName, out string lastName)
    {
        firstName = FirstName;
        lastName = LastName;
    }
}

I suppose the idea of using our variables in the desconstructor instead of directly returning a tuple is so that you can have different overloads of the deconstructor. However, I do not seem to be able to deconstruct the object to three variables. I can only deconstruct it to two variables.

For example, this does not compile:

(string firstName, string lastName, string company) = customer;

And I get this error:

"Cannot deconstruct a tuple of '2' elements into '3' variables."

But this does and works:

(string firstName, string lastName) = customer;

What am I missing?

like image 664
Milen Kovachev Avatar asked Jan 30 '17 09:01

Milen Kovachev


1 Answers

You have called your methods, Deconstructor, rather than Deconstruct. Also, you can't redeclare firstName and lastName in the two tuples. Make those change, and the following lines of code all compile just fine:

var customer = new Customer("a", "b");
(string firstName1, string lastName1, string company) = customer;
(string firstName2, string lastName2) = customer;
like image 104
David Arno Avatar answered Sep 23 '22 01:09

David Arno