1

Why does this:

System.Collections.Stack s = new Stack();
s.Push(97);
char c = (char) s.Pop(); //throws InvalidCastException

throw an error, but this:

char c = (char) 97; //c = 'a'

work just fine?

I'm especially confused since s.Pop().GetType() returns System.Int32, so it really shouldn't matter... What's going on here? Am I missing something, or do I have to work around it?

hensing1
  • 187
  • 13

2 Answers2

1

Because Stack is the non-generic variant of a stack implementation. Pop returns an object, and the cast object -> char is invalid.

This does work though:

char c = (char)(int)s.Pop();

My two cents: use a generic implementation of Stack:

`Stack<char> s = new Stack<char>();`
Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325
0

Use a generic version of Stack<T> like

Stack<int> s = new Stack<int>();
s.Push(97);
char c = (char)s.Pop();
Console.WriteLine(c);
Rahul
  • 76,197
  • 13
  • 71
  • 125