theonlygusti theonlygusti - 1 month ago 7
C# Question

is a 'field' but is used like a type - C#

I have to create an implementation of a stack.

I want to create a class that I can use like so:

Stack<string> myStack = new Stack<string>();

myStack.Push("Harold");
myStack.Push("Evie");

myStack.Pop(); // => "Evie"


Here's what I've written so far:

public class Stack<T> {
private T[] stack;
private int stackPointer;

public Stack<T>() {
this.stackPointer = -1;
}
}


But already I am getting this error from VS:

this.stackPointer = -1;
// ERROR: stackPointer is a field but is used like a type.


What does this mean and how do I fix it? (Note I am extremely new to C#)

Answer Source

Try removing the type in the constructor, like this:

public class Stack<T> {
    private T[] stack;
    private int stackPointer;

    public Stack() {
        this.stackPointer = -1;
    }
}

Take a look at this Microsoft article about generics which actually includes an implementation of a generic stack class.

enter image description here