-
Notifications
You must be signed in to change notification settings - Fork 5.2k
Closed
Labels
api-approvedAPI was approved in API review, it can be implementedAPI was approved in API review, it can be implementedapi-suggestionEarly API idea and discussion, it is NOT ready for implementationEarly API idea and discussion, it is NOT ready for implementationarea-System.Collectionshelp wanted[up-for-grabs] Good issue for external contributors[up-for-grabs] Good issue for external contributors
Milestone
Description
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.
AgentFire, ViIvanov, loic-sharma, mattjohnsonpint and omariom
Metadata
Metadata
Assignees
Labels
api-approvedAPI was approved in API review, it can be implementedAPI was approved in API review, it can be implementedapi-suggestionEarly API idea and discussion, it is NOT ready for implementationEarly API idea and discussion, it is NOT ready for implementationarea-System.Collectionshelp wanted[up-for-grabs] Good issue for external contributors[up-for-grabs] Good issue for external contributors