1

I am trying to print the contents of a Stack.

Stack Class

When I make the attempt I get the following error.

Unhandled exception. System.NullReferenceException: Object reference not set to an instance of an object.

Which is happening on the foreach line of my code. I'm unsure why this is happening since I thought I was using the example given on the page I linked. Example would be...

        foreach( string number in numbers )
        {
            Console.WriteLine(number);
        }

Following is my code. Everything appears to be functional except this part which throws the error.

            foreach(var s in stack)
            {
                Console.WriteLine(s);
            }

...and this is my code.

using System;

namespace Exercise
{
    class Program
    {
        static void Main()
        {
            var stack = new Stack();
            stack.Push(1);
            stack.Push(2);
            stack.Push(3);

            foreach(var s in stack)
            {
                Console.WriteLine(s);
            }
        }
    }
}
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;

namespace Exercise
{
    internal class Stack : IEnumerable
    {
        private object _object;
        private List<object> list = new List<object>();
        private IEnumerator Enumerator;
        public IEnumerator GetEnumerator() => Enumerator;

        internal object Pop()
        {
            if (list.Count == 0)
                throw new InvalidOperationException("Cannot use .Pop() if list count equals 0.");

            _object = list.FirstOrDefault();

            list.RemoveAt(0);

            return _object;
        }

        internal void Push(object obj)
        {
            _object = obj;

            if (_object == null)
                throw new InvalidOperationException("Cannot use .Push() if object is null.");

            list.Insert(0, _object);
        }

        internal void Clear()
        {
            if (list.Count == 0)
                throw new InvalidOperationException("Cannot use .Clear() if list is empty.");

            list.Clear();
        }
    }
}

What am I doing wrong and how can I fix this to print the contents of the stack?

0

1 Answer 1

3

Your GetEnumerator method returns null because the field Enumerator was never explicitly initialized, so it got the default value null.

Then, the foreach loop calls .GetEnumerator(), receives a null and tries to access the .Current property of null, so you get a NullReferenceExcpetion.

To fix this, you can use the following implementation:

public IEnumerator GetEnumerator()
{
    while (list.Any())
        yield return Pop();
}
Sign up to request clarification or add additional context in comments.

2 Comments

I like your solution, but it doesn't Enumerate the entire collection because you're increasing i as list.Count decreases. In this example, when list.Count is 1, i is 2, and the for loop ends. Instead, use while (list.Any()).
Thank you Gur Galler for that. That was what I was missing. Also, thank you @rfmodulator for mentioning the fix to Gur Galler code. Everything works now.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.