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);
}
}
Nicholas Paldino [.NET/C# MVP] - 05 Nov 2007 17:58 GMT
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.

Signature
- Nicholas Paldino [.NET/C# MVP]
- mvp@spam.guard.caspershouse.com
> Hi,
>
[quoted text clipped - 45 lines]
> }
> }
not_a_commie - 06 Nov 2007 09:49 GMT
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.