I am trying to print the contents of a Stack.
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?
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();
}