Last active
December 24, 2017 18:29
-
-
Save mjs3339/d56aaf4ab00d2c8d2463a1376a3b4cfe to your computer and use it in GitHub Desktop.
C# Tiny Generic Array Class
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[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