Quote:
In particular, it would be fine if I could just return an unmodifiable List<string> of the keys in the dictionary. Then I could just add another function to return the value for a specified key.
That sounds like the way to go, since it will avoid creating a copy of the dictionary on every access.
I'd be inclined to have the container class implement
IReadOnlyDictionary(TKey, TValue)[
^]:
public class Foo : IReadOnlyDictionary<string, string>
{
private readonly Dictionary<string,string> _records = new Dictionary<string,string>();
public int Count => _records.Count;
public IEnumerable<string> Keys => _records.Keys;
public IEnumerable<string> Values => _records.Values;
public string this[string key] => _records[key];
public bool ContainsKey(string key) => _records.ContainsKey(key);
public bool TryGetValue(string key, out string value) => _records.TryGetValue(key, out value);
public IEnumerator<KeyValuePair<string, string>> GetEnumerator() => _records.GetEnumerator();
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
}
NB: You might be tempted to just cast the
_records
field to an
IReadOnlyDictionary<string, string>
and return that. But that wouldn't prevent the calling code from casting it back to a
Dictionary<string, string>
and modifying it.
Depending on your requirements, you might also want to take a look at
the Immutable Collections[
^] package.