StackOverflowException when serializing

  • Thread starter Thread starter etienne.maitre
  • Start date Start date
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);
}
}
 
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.
 
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.
 
Back
Top