D
D
dimx142015-12-23 17:56:20
C++ / C#
dimx14, 2015-12-23 17:56:20

Stack implementation as c# array, what's causing the error?

Gives an error: "Using the generic type 'ConsoleApplication1.CStack' requires an argument of type '1'".
namespace ConsoleApplication1
{
public class CStack
{
private T[] _array; //array for storing data of type T
private const int defaultCapacity = 10; //default capacity, then you can expand
private int size; //size
public CStack()
{ //constructor
this.size = 0;
this._array = new T[defaultCapacity];
}
public bool isEmpty() //test for emptiness
{
return this.size == 0;
}
public virtual int Count //parameter for displaying the size
{
get
{
return this.size;
}
}
public T Pop() // method of taking from the top
{
if (this.size == 0)
{ // throwing an error when taking from an empty stack (Overflow)
throw new InvalidOperationException();
}
return this._array[--this.size];
}
public void Push(T newElement)
{
if (this.size == this._array.Length) //if we have overflow...
{ //I know it's not optimal, but this is c#...
T[] newArray = new T[2 * this._array.Length];
Array.Copy(this._array, 0, newArray, 0, this.size);
this._array = newArray; //just create a new double-sized array
}
this._array[this.size++] = newElement; //insert element
}
public T Peek()
{
if (this.size == 0)
{
throw new InvalidOperationException();
}
return this._array[this.size - 1];
}
}
class Program
{
static void Main(string[] args)
{
CStack stack = new CStack();
stack.Push(3);
stack.Push(18);
Console.WriteLine("element Number " + stack.Count.ToString() + " is " + stack.Pop().ToString());
Console.WriteLine("element Number " + stack.Count.ToString() + " is " + stack.Pop().ToString());
Console.ReadLine();
}
}
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Kovalsky, 2015-12-23
@dimx14

Excuse me, but where do you actually create T. Is it a generic? Then your class should be CStack<T>
By code:
POP method - where do you remove an element from the list? Or will he continue to lie there? And if the type is heavy?
Where do you get such love for this?
I would also replace the exception with my own - "The stack is empty". You are throwing InvalidOperationException without explanation. How am I, as a client, supposed to guess what happened?
PS A stack is NOT an array. The stack is a linked list with a LIFO bypass rule. Each object must have a reference to the next object on the stack.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question