What is the main difference both of them and which one is better. can we add mix of data in both or not. what is the difference between
Stack st = new Stack()
and
Stack<string> names = new Stack<string>();
What is the main difference both of them and which one is better. can we add mix of data in both or not. what is the difference between
Stack st = new Stack()
and
Stack<string> names = new Stack<string>();
in this case Stack<string> names = new Stack<string>();
you can put only "string" in the stack, and in this Stack st = new Stack();
you can put any objects.
These are two different collections. The first one is in the namespace System.Collections
and the second one in the namespace System.Collections.Generic
.
The first one (the non-generic one) stores values of type object
.
public virtual void Push(object obj)
public virtual object Pop()
Since all types in C# derive from object
, you can store any kind of value in this stack. The drawback is, that value types must be boxed, i.e. encapsulated into an object, before being added to the collection. While being retrieved they must be unboxed. Also you have no type safety.
Example:
Stack st = new Stack();
st.Push("7");
st.Push(5); // The `int` is boxed automatically.
int x = (int)st.Pop(); // 5: You must cast the object to int, i.e. unbox it.
int y = (int)st.Pop(); // "7": ERROR, we inserted a string and are trying to extract an int.
The second one is generic. I.e. you can specify the type of item that the stack is intend to store. It is strongly typed.
public void Push(T item)
public T Pop()
In your example with new Stack<string>()
T
is replaced by string
public void Push(string item)
public string Pop()
Example:
Stack<string> names = new Stack<string>();
names.Push("John");
names.Push(5); // Compiler error: Cannot convert from 'int' to 'string'
string s = names.Pop(); // No casting required.
Not that the first example produces an exception at runtime (which is bad), while the second produces a compiler error and informs you about the problem while you are writing the code.
Advice: Always use the generic collections.