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.
Background and motivation
Like the
List<T>has a methodAsReadOnly()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
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.