Compiler implementation strategy for dictionary expressions targeted to IReadOnlyDictionary<TKey, TValue>
#78101
Labels
IReadOnlyDictionary<TKey, TValue>
#78101
The implementation strategy for the compiler for C# 14 when targeting a dictionary expression against
IReadOnlyDictionary<TKey, TValue>
should be very close to as follows:Note:
ReadOnlyDictionary<TKey,TValue>
(and its Dictionary-taking constructor) is available on:As such, the type and constructor can effectively always be depended on as a reliable backstop for emitting. We can error if we need this type and it is not available.
Required:
[]
should be emitted asReadOnlyDictionary<,>.Empty
when available (.Net 8+). Or a<private_impl>.ReadOnlyDictionary<TKey, TValue>.Empty = new(new())
static field we emit, if not available.[...]
should emit using aFrozenDictionary<,>
when assigned to a static readonly field, and when that type is available. The compiler should pass the keys/values in the collection expression to the appropriate factory method. Exact factory method TBD, but we expect there to be one that takes aReadOnlySpan<KeyValuePair<,>>
that we can look for.[...]
should otherwise emit asnew ReadOnlyDictionary<,>(Dictionary<,> __tempStorage)
. Where the compiler places the values into__tempStorage
first, using its indexer, and then wraps that with aReadOnlyDictionary<,>
.Optional:
Future optimizations are allowed in this space. For example, emitting
[...]
as as some specialized impl if the count of elements is fixed and very small. For example, a dict optimized for the single element case. And perhaps a specialized 2-N element dictionary that just has things in linear storage when N is very small. This would need good measurements to ensure the user value was there both when creating the dictionary and when consuming it.Any specialized impl would have to abide by the contract of
IReadOnlyDictionary<TKey, TValue>
as well as the additional rules and recomendations placed by the language specification. Specifically:--
Note
with(...)
support forIReadOnlyDictionary<,>
is yet to be finalized. However, we will very likely have support forwith(IEqualityComparer<TKey> comparer)
for the user to supply a custom comparer. This should be possible with the above translation rules, just passing the comparer along appropriately.The text was updated successfully, but these errors were encountered: