Skip to content

[API Proposal]: Add extension method AsReadOnly() for IDictionary<TKey, TValue> #33033

@Mrxx99

Description

@Mrxx99

Background and motivation

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.

API Proposal

namespace System.Collections.Generic
{
    public static class CollectionExtensions
    {
+       public static ReadOnlyDictionary<TKey, TValue> AsReadOnly(this IDictionary<TKey, TValue> dictionary)
+            => new ReadOnlyDictionary<TKey, TValue>(dictionary);
    }
}

API Usage

private Dictionary<string, string> _theDictionary = new Dictionary<string, string>();

public IReadOnlyDictionary<string, string> TheDictionary => _theDictionary.AsReadOnly();

Alternative Designs

The origianl proposal (as can be read in the comments, an extension method is preferred):

public class Dictionary<TKey, TValue> : IDictionary<TKey, TValue>, IDictionary...
{
+        public ReadOnlyDictionary<TKey, TValue> AsReadOnly()
+            => new ReadOnlyDictionary<TKey, TValue>(this);
}

Risks

I don't see any it's just one extension method more calling a very common constructor.

Metadata

Metadata

Assignees

Labels

api-approvedAPI was approved in API review, it can be implementedapi-suggestionEarly API idea and discussion, it is NOT ready for implementationarea-System.Collectionshelp wanted[up-for-grabs] Good issue for external contributors

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions