C#.NET Stack (non-generic): is the following mixed-type Push() usage valid? Stack st = new Stack(); st.Push("hello"); st.Push(8.2); st.Push(5); st.Push('b'); st.Push(true);

Difficulty: Easy

Correct Answer: Valid: non-generic Stack stores objects, so dissimilar elements are allowed.

Explanation:


Introduction / Context:
The classic System.Collections.Stack is a non-generic last-in, first-out collection that stores elements as System.Object. This permits mixing types in the same collection, which is sometimes useful and sometimes risky.



Given Data / Assumptions:

  • We are using System.Collections.Stack (non-generic), not Stack.
  • We push strings, floating-point numbers, integers, a char, and a bool.


Concept / Approach:
Because the non-generic Stack stores elements as object references, any type can be pushed (value types are boxed automatically). Type safety is enforced at use-sites via casts when popping or peeking.



Step-by-Step Solution:

Check string → allowed (reference type).Check double/float literal → allowed (boxed value type).Check int → allowed (boxed value type).Check char literal 'b' → allowed (boxed value type).Check bool → allowed (boxed value type).


Verification / Alternative check:
Run-time: foreach over st will yield objects of different types. Casting back to original types works as long as you cast correctly (or check with 'is'/pattern matching) before use.



Why Other Options Are Wrong:
A/D assume homogeneity requirement or a special API—non-generic Stack has neither. B forbids bool—false. C confuses char vs. string; 'b' is valid for char.



Common Pitfalls:
Mixing types can lead to InvalidCastException when popping if you assume the wrong type. Prefer Stack for compile-time safety.



Final Answer:
Valid: non-generic Stack stores objects, so dissimilar elements are allowed.

More Questions from Collection Classes

Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion