-
So I'm trying to make this statement work w/ new the new Collection Expressions public static Dictionary<string, string> StringDict = [("Value1", "Value2")]; The error received is Reading the documentation about construction of types which implement public static void Add<TKey, TVal>(this Dictionary<TKey, TVal> dict, (TKey key, TVal val) item)
where TKey : notnull => dict.Add(item.key, item.val); This doesn't work however. Experimenting a bit with my own type though revealed an odd inconsistency between the behavior with regards to the generic and non-generic versions of IEnumerable. public class BasicDict<TKey, TVal> : System.Collections.IEnumerable { ... }
public class GenericDict<TKey, TVal> : System.Collections.Generic.IEnumerable<int> { ... }
public static class DictExt
{
public static BasicDict<string, string> StringDict1 = [("Value1", "Value2")]; // Works
public static GenericDict<string, string> StringDict2 = [("Value1", "Value2")]; // Fails
public static BasicDict<string, string> StringDict3 = new() { ("Value1", "Value2") }; // Works
public static GenericDict<string, string> StringDict4 = new() { ("Value1", "Value2") }; // Works
public static void Add<TKey, TVal>(this BasicDict<TKey, TVal> dict, (TKey key, TVal val) item) { ... }
public static void Add<TKey, TVal>(this GenericDict<TKey, TVal> dict, (TKey key, TVal val) item) { ... }
} The compiler appears to be able to find and use my Add extension method when we implement The same behavior persists not just for extensions, but for class methods as well. Is this difference in lookup behavior intentional? From the outside it appears mildly buggy. Is there some reason that the argument to |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 10 replies
-
We do not yet have support for dictionaries in collection expressions. That work is currently scheduled for C# 13; at that point, we hope to have a syntax closer to |
Beta Was this translation helpful? Give feedback.
-
However, there is a bearable alternative (#7666 (comment)): public static Dictionary<string, string> StringDict = [new("Value1", "Value2")]; |
Beta Was this translation helpful? Give feedback.
-
If you want just that syntax (but probably not the efficiency), MyDictionary<string, string> StringDict = [("Value1", "Value2")];
public class MyDictionary<TKey, TValue> : IEnumerable<(TKey, TValue)>
{
public Dictionary<TKey, TValue> Dictionary { get; } = new();
public void Add((TKey, TValue) item)
=> Dictionary.Add(item.Item1, item.Item2);
} |
Beta Was this translation helpful? Give feedback.
We did that for a few reasons: first, we're concerned about the stability of the error experience, and second,
IEnumerable
(non-generic) scenarios are generally in legacy collection types that we don't intend to fully support. You can read the notes from the meeting that elaborate these reasons more completely: https://github.com/dotnet/csharplang/blob/main/meetings/2023/LDM-2023-10-02.md#collection-expressions.