Question

Having the class as following

public class MyGeneric<T> : IEnumerable
{
    public System.Collections.IEnumerator GetEnumerator()
    {
        return this.GetEnumerator();
    }

    public void Add(T item)
    {
        this.Add(item);
    }

    public IEnumerable<T> GetNullItems()
    {
        foreach (T item in this)
        {
            if (item != null)
            {
                yield return item;
            }
        }
    }
}

when I instantiate an object of type MyGeneric and add items to it I get a System.StackOverflowException

MyGeneric<int?> mylist = new MyGeneric<int?>()
{
    1,null,3,null,5,6,7,null,9,10
};

The problem is that when I add 1 the Add method is called, and inside Add method the code snippet this.Add(item); means call Add again, whereas I meant to add the item to the collection.

If I delete the Add method I get a 'MyClass.MyGeneric' does not contain a definition for 'Add' error.

I'm confused, how should I add the item?

Was it helpful?

Solution

Well, sure.

public void Add(T item)
{
    this.Add(item);
}

Here you have a method that calls itself, which in turn calls itself, which in turn calls itself, until you run out of stack.

You probably want to add a field of type List<T>, and have your Add method call _list.Add(item);. Or write the new item to disk, or store it wherever else you want -- but a list would be the most common place to store it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top