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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With