1

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 :)

1
  • 1
    May I wonder why you're not using List<string> instead? As you get all this out of the box? Commented Mar 5, 2011 at 9:51

1 Answer 1

2

Rather than ele.Equals(Value), use EqualityComparer<T>.Default.Equals(ele, Value); this will work correctly with null (for reference-types), Nullable<T> (for value-types), types that implement IEquatable<T>, and any other types using object.Equals.

You might want to cache it, though:

var comparer = EqualityComparer<T>.Default;
//loop
   if(comparer.Equals(ele,Value)) {...}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.