-
Is it possible to use deconstruct for an interface? For example, we could use var dic = new Dictionary<string, string>();
foreach (var (key, value) in dic) |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
The short answer is yes, any type can support custom deconstruction via extension methods. However, if you're referring to the non-generic public static class IDictionaryExtensions {
// returns a type-safe enumerable of each entry
public static IEnumerable<DictionaryEntry> Entries(this IDictionary dictionary) {
foreach (DictionaryEntry entry in dictionary) {
yield return entry;
}
}
// deconstruct each entry
public static void Deconstruct(this DictionaryEntry entry, out object key, out object value) {
key = entry.Key;
value = entry.Value;
}
} Then you can use it like this: IDictionary dictionary = ...;
foreach (var (key, value) in dictionary) {
// ...
} However, the key and value will both be of type |
Beta Was this translation helpful? Give feedback.
The short answer is yes, any type can support custom deconstruction via extension methods.
However, if you're referring to the non-generic
System.Collections.IDictionary
this is complicated by the fact that it implementsSystem.Collections.IEnumerable
which effectively enumerates all values asSystem.Object
. An extension method to deconstructSystem.Object
is possible but wouldn't apply in most situations, so what I might suggest is an extension method onIDictionary
that returnsIEnumerable<DictionaryEntry>
which would be safe to deconstruct: