Skip to content

Instantly share code, notes, and snippets.

@Tewr
Last active June 4, 2018 11:58
Show Gist options
  • Save Tewr/cce6acd27808c163b687cf22fd33c9a1 to your computer and use it in GitHub Desktop.
Save Tewr/cce6acd27808c163b687cf22fd33c9a1 to your computer and use it in GitHub Desktop.
ReadOnly Empty Dictionary implementation
using System.Linq;
namespace System.Collections.Generic
{
public class EmptyReadOnlyDictionary<TKey, TValue> : IReadOnlyDictionary<TKey, TValue>
{
private static readonly Lazy<IEnumerable<KeyValuePair<TKey, TValue>>> Empty =
new Lazy<IEnumerable<KeyValuePair<TKey, TValue>>>(Enumerable.Empty<KeyValuePair<TKey, TValue>>);
public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator() => Empty.Value.GetEnumerator();
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
public int Count { get; } = 0;
public bool ContainsKey(TKey key) => false;
public bool TryGetValue(TKey key, out TValue value)
{
value = default;
return false;
}
public TValue this[TKey key] => throw new KeyNotFoundException();
public IEnumerable<TKey> Keys => Enumerable.Empty<TKey>();
public IEnumerable<TValue> Values => Enumerable.Empty<TValue>();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment