C# 7 array deconstruction
Some of you might know that python has much semantic sugar implemented by default. One thing I want to focus on now it array deconstruction. I show you what I mean, just to make sure that we talk about the same thing.
What happens if we try the same thing in C# 7?
This throws an error when compiling, but the error was interesting for me, it said:
No suitable Deconstruct instance or extension method was found for type ‘string[]’, with 2 out parameters and a void return type.
It says that there is a Deconstruct
method missing… so let´s try to implement one, maybe as extension method.
Now, with this extension method let´s try it again!
OMG, this acutally works! Let’s try to make this a bit more generic:
And it turns out this works! Amazing, we can do array deconstructing in C# 7 with the efford of some simple extension methods!
Conclusion
As we have seen with a bit of extra efford you can do array deconstrution in C# 7. I am really wondering why those extensions methods do not exist by default? But we could easily generate them using a simple T4 template.
Thank you for reading!