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

In C # 7, we can implement the Deconstruct method, which will be called when an object is assigned to a tuple with the corresponding types.

I wonder why Microsoft decided to implement this as a "magic method." There is this specially named method that is not inherited anywhere, and if you name it correctly and place the correct parameters, then you can assign this object to the appropriate tuple.

I would suggest that the development team create an interface for this purpose.

Sort of:

 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 should be more interfaces with a different number of parameters.

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

+5
source share
1 answer

Since it is the way it is with Deconstruct, you can overload it and apply it to any object. If it were an interface, then the team would have to go back and apply it to every type that they need in order to have it, and they would need to have different methods for each signature, which is simply not possible. For instance.

 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; } } 

In the current implementation, you can have three versions of Deconstruct. Alternatively, you can apply the Deconstruct method as an extension method. These patterns would not be possible with a single interface.

+10
source

Source: https://habr.com/ru/post/1272096/


All Articles