I'm learning about generics, so I'm trying to make my own generic array class, which I can use to make an array of strings or an array of numeric data. This generic class has some different methods, forExample, I can add data and remove data, and search for data. All these methods works like a charm with numeric data, but I'm having some problems with making it work with strings, since it's a reference type and the default value is null, which makes my methods throw null exceptions.
My Class looks like this:
class MyArray<T> : IComparable<T>, IEnumerable<T>, IEnumerator<T>
{
T[] data = new T[10];
private int currentIndex = 0;
//This method works as intended, both with strings and ints
public void Add(T Value)
{
data[currentIndex] = Value;
currentIndex++;
if (currentIndex == data.Length)
{
T[] tmp = new T[data.Length + 10];
data.CopyTo(tmp, 0);
data = tmp;
}
}
//Can't figure out how to make this method work with strings
public void RemoveItem(T Value)
{
T[] tmp = new T[data.Length - 1];
int i = 0;
foreach (T ele in data)
{
if (!ele.Equals(Value))//This line gives me a nullRefException when I'm using strings
{
tmp[i] = ele;
i++;
}
}
data = tmp;
}
My Main form where I'm adding the data and trying to remove it looks like this:
static void Main(string[] args)
{
MyArray<string> StringArray = new MyArray<string>();
StringArray.Add("1");
StringArray.Add("2");
StringArray.RemoveItem("2");
}
I can't figure out a clever way to remove the data again, when it's a string, because of the default value of null.
Thanks in advance :)
List<string>instead? As you get all this out of the box?