I am implementing a generic stack using array. But i get error as :
Cannot apply indexing with [] to an expression of type 'T'
on the line:
data[SP] = data;
how to fix the issue? also i checked this link:
Cannot apply indexing to an expression of type 'T'
should i implement the same fix here in my situation too? or is there any other best option available?
Here is my code:
public class MyStack<T>
{
private T[] data { get; set; }
private int SP { get; set; }
private int Capacity { get; set; }
public MyStack(int capacity)
{
this.Capacity = capacity;
data = new T[Capacity];
SP = -1;
// it works here, dont know why??? ;)
data[0] = default(T);
}
public void Push(T data)
{
++SP;
if(SP>=Capacity) growArray();
// This is where i get error.
data[SP] = data;
}
public T Pop()
{
if (SP < 0) throw new InvalidOperationException();
T value = data[SP];
data[SP] = default(T);
SP--;
return value;
}
public T Peak()
{
if (SP < 0) throw new InvalidOperationException();
return data[SP];
}
private void growArray()
{
throw new NotImplementedException();
}
}
Thanks in advance.
System.Collections.Generic.Stack<T>