views:

1390

answers:

1

All I am trying to do is

XmlSerializer serializer = new XmlSerializer(typeof(Stack<int>));

and I get the following at runtime:

System.InvalidOperationException: You must implement a default accessor on System.Collections.Generic.Stack`1 [[System.Int32, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]] because it inherits from ICollection.

Am I not supposed to serialize the Stack<int>?

+2  A: 

Since the Stack class does not have a default accessor (by index for example) you cannot serialize it with that method.

I would suggest copying your stack to a List then serializing the list.

List<int> serializableLIst = new List<int>( myStack );
XmlSerializer serializer = new XmlSeralizer(typeof(List<int>));

See if that doesn't work better.

palehorse
It does work, thanks! It would be interesting to know why the framework designers decided not to support serialization on the Stack<T> itself...
They do not provide the default accessor for the stack. You cannot say x = myStack[3] for example. The Stack operates differently than a normal collection so the accessor is not implemented on it.
palehorse