Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# 7: Why is tuple deconstruction not implemented through an interface?

Tags:

.net

c#-7.0

In C# 7 we can implement a Deconstruct method that will be called when assigning an object to a tuple with the matching types.

I am wondering why did Microsoft decide to implement this as a "magic method". There is this specifically named method that isn't inherited from anywhere and if you name it right and put the correct parameters, then you will be able to assign this object to the respective tuple.

I would imagine, that the design team would create an interface for this purpose.

Something like:

public interface IDecontructible<T1>
{
    void Deconstruct(out T1 a);
}

public interface IDecontructible<T1, T2>
{
    void Deconstruct(out T1 a, out T2 b);
}

public interface IDecontructible<T1, ... ,Tn>
{
    void Deconstruct(out T1 a, ... ,out Tn n);
}

Of course there would have to be more interfaces with different number of parameters.

Is there any obvious reason for this design choice, that I am missing?

like image 548
Filip Minx Avatar asked Sep 25 '17 12:09

Filip Minx


1 Answers

Because with Deconstruct the way it is, you you can overload it, and it can apply to any object. If it were an interface, then the team would have to go back and apply it to every type they want the capability to have it, and they would need to have different ones for each method signature, which just isn't feasible. For example.

class Employee {
   public string FirstName {get;set;}
   public string Id {get;set;}

   Deconstruct (out string firstName){
    firstName = FirstName;
   }

   Deconstruct (out string firstName, out string LastName){
    firstName = FirstName;
    lastName = LastName;
   }

   Deconstruct (out int id){
    id = EmployeId; 
   }
}

With the current implementation, you can have three versions of Deconstruct. Also, you can apply the Deconstruct method as an Extension Method. These patterns wouldn't be possible with a single interface implementation.

like image 141
kemiller2002 Avatar answered Sep 29 '22 11:09

kemiller2002