In an earlier post, we explored the Deconstruct feature for Non-Tuples. It was a pretty useful feature that came along in the 7.x series . If one does have access to source, adding deconstruct is quite easy. But what about classes we do not have (source code) access to ? For example, the .Net framework classes ? Can we add a deconstruct to it ? It turns out, it is quite simple as well. Extension Methods allows us to add deconstruct to existing classes without breaking the Open Closed Principle.
For demonstration purpose, let us write a deconstruct for Point Class under the System.Drawing namespace.
public static class ExtensionMethods { public static void Deconstruct(this Point source,out double x,out double y) { x = source.X; y = source.Y; } } void Main() { Point point = new Point(100,500); var (x,y) = point; Console.WriteLine($"Point.X={x},Point.Y={y}"); }
As observed, it is quite easy to add deconstruct to your existing classes using the Extension Methods.