Runtime: Add Dictionary<T>.AsReadOnly()

Created on 1 Mar 2020  路  3Comments  路  Source: dotnet/runtime

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);
}
api-suggestion area-System.Collections

Most helpful comment

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

All 3 comments

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.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

sahithreddyk picture sahithreddyk  路  3Comments

GitAntoinee picture GitAntoinee  路  3Comments

nalywa picture nalywa  路  3Comments

iCodeWebApps picture iCodeWebApps  路  3Comments

yahorsi picture yahorsi  路  3Comments