StackOverflowException when serializing

E

etienne.maitre

Hi,

I work against .NET 2.0 using C# 2.0. I am facing a problem trying to
serialize the class foo (given below). Basically, foo can contain
other foos in a list. When I try to create a serializer, using the
test() method below, I get a superb StackOverflowException. I googled
for it but didn't found any answer to why I got this exception and how
to serialize foo.

Any help accepted :)

Thanks,

public void test()
{
XmlSerializer serializer = new XmlSerializer(typeof(foo));
....
}

[Serializable]
public class foo : IEnumerable<foo>
{
// ... some members...
List<foo> g;

public foo()
{
g = new List<foo>();
}

public IEnumerator<foo> GetEnumerator()
{
foreach (foo element in g)
{
yield return element;
}
}

System.Collections.IEnumerator
System.Collections.IEnumerable.GetEnumerator()
{
return GetEnumerator();
}

public void Add(Object e)
{
g.Add(e as foo);
}
}
 
N

Nicholas Paldino [.NET/C# MVP]

The problem here comes from the fact that you are implementing
IEnumerable<T> on T itself (in this case foo). You are better of creating a
container class which implements IEnumerable<foo> and then serialize that.

Also, you don't need to the Serializable attribute when using XML
Serialization.
 
N

not_a_commie

Your foo.g member is recursive. You need an object-reference type of
serialization. The easiest fix for you would be to upgrade to WCF
(.NET 3.0) and use the DataContractSerializer with its support for
object references.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top