Skip to content

Instantly share code, notes, and snippets.

@mjs3339
Last active December 24, 2017 18:29
Show Gist options
  • Save mjs3339/d56aaf4ab00d2c8d2463a1376a3b4cfe to your computer and use it in GitHub Desktop.
Save mjs3339/d56aaf4ab00d2c8d2463a1376a3b4cfe to your computer and use it in GitHub Desktop.
C# Tiny Generic Array Class
[Serializable]
public class TinyArray<T>
{
public int Count;
public T[] Thing;
public TinyArray() : this(4096)
{
}
public TinyArray(int cap)
{
Count = 0;
Thing = new T[cap];
}
public T this[int index]
{
get
{
if (index > Count)
throw new Exception("Error: Index out of range.");
return Thing[index];
}
set
{
EnsureSize();
Thing[index] = value;
Count++;
}
}
private void EnsureSize()
{
if (Count + 1 > Thing.Length)
{
var NewLength = Thing.Length == 0 ? 4096 : Thing.Length * 2;
var newtArray = new T[NewLength];
Array.Copy(Thing, 0, newtArray, 0, Count);
Thing = newtArray;
}
}
public void Add(T item)
{
EnsureSize();
Thing[Count] = item;
Count++;
}
public T[] ToArray()
{
var newtArray = new T[Count];
Array.Copy(Thing, 0, newtArray, 0, Count);
return newtArray;
}
public void Clean()
{
var newtArray = new T[Count];
Array.Copy(Thing, 0, newtArray, 0, Count);
Thing = newtArray;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment