Skip to content

Instantly share code, notes, and snippets.

@airbreather
Last active August 29, 2015 14:12
Show Gist options
  • Save airbreather/1d9e709e17594920fd0f to your computer and use it in GitHub Desktop.
Save airbreather/1d9e709e17594920fd0f to your computer and use it in GitHub Desktop.
public sealed class ArrayWrapper<T> : IReadOnlyDictionary<int, T>
{
private readonly T[] arr;
public ArrayWrapper(T[] arr)
{
if (arr == null)
{
throw new ArgumentNullException("arr");
}
this.arr = arr;
}
public int Count { get { return this.arr.Length; } }
public T this[int key] { get { return this.arr[key]; } }
public IEnumerable<int> Keys { get { return Enumerable.Range(0, this.arr.Length); } }
public IEnumerable<T> Values { get { return this.arr.Skip(0); } }
public IEnumerator<KeyValuePair<int, T>> GetEnumerator()
{
return new Enumerator(this.arr);
}
IEnumerator IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
public bool ContainsKey(int key)
{
return 0 <= key &&
key < this.arr.Length;
}
public bool TryGetValue(int key, out T value)
{
if (this.ContainsKey(key))
{
value = this.arr[key];
return true;
}
value = default(T);
return false;
}
private sealed class Enumerator : IEnumerator<KeyValuePair<int, T>>
{
private readonly T[] arr;
private int idx = -1;
public Enumerator(T[] arr)
{
this.arr = arr;
}
public KeyValuePair<int, T> Current { get { return new KeyValuePair<int, T>(this.idx, this.arr[idx]); } }
object IEnumerator.Current { get { return this.Current; } }
public bool MoveNext()
{
return (++this.idx) < this.arr.Length;
}
public void Reset()
{
this.idx = -1;
}
void IDisposable.Dispose()
{
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment