Like the List<T> has a method AsReadOnly() I would like to propose the same for the Dictionary.
This could lead to more clean and fluent code, when you can call AsReadOnly at the end of a call chain instead of creating a new instance of ReadOnlyDictionary manually.
I am aware that Dictionary already implements IReadOnlyDictionary but only using the ReadOnlyDictionary it is really immutable without the possibility to cast it back to (I)Dictionary.
public class Dictionary<TKey, TValue> : IDictionary<TKey, TValue>, IDictionary...
{
+ public ReadOnlyDictionary<TKey, TValue> AsReadOnly()
+ => new ReadOnlyDictionary<TKey, TValue>(this);
}
I was scratching my head thinking about this proposal.
If we need the functionality i would be more opt to extension function or default interface implementation for IDictionary<,>
public ReadOnlyDictionary<TKey, TValue> AsReadOnly(this IDictionary<TKey, TValue> dictionary) => new ReadOnlyDictionary<TKey, TValue>(dictionary)
as this will cover more than just Dictionary.
also this is already used in runtime/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/MetadataServices.cs for example.
I'm not very convinced we need it at all.
IMHO we should go more in the #31573 direction
We'd probably want to express this as an extension method due to codegen size concerns. How about this?
namespace System.Collections.Generic
{
public static class CollectionExtensions
{
+ public static ReadOnlyDictionary<TKey, TValue> AsReadOnly(this IDictionary<TKey, TValue> dictionary)
+ => new ReadOnlyDictionary<TKey, TValue>(dictionary);
}
}
cc @jkotas @GrabYourPitchforks
I agree, I think it does make more sense as extension method.
Most helpful comment
We'd probably want to express this as an extension method due to codegen size concerns. How about this?
cc @jkotas @GrabYourPitchforks