Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# How do you solve a circular object reference

I've run into what i belive could be a major issue for my code design and i was hoping someone here could explain to me how i would work around the issue.

I have 2 classes which each have a property of the other class creating a circular reference. I plan on serializing these classes and using XSLT to format the output but i'm assuming this will fail due to the circular reference.

Example

public class Book
{
  public BookShop TheShop = new BookShop();
}
public class BookShop
{
  list<Book> Books = new list<Book>();
}

So from this example each book will be in a bookShop and each bookshop will have many books. If i serialize the bookshop it will then serialize each book which then serialize a bookshop and so on round and round. How should i handle this?

like image 563
Jammy Avatar asked Dec 01 '25 20:12

Jammy


2 Answers

Tag TheShop with an attribute to prevent its serialization.

[XmlIgnore] with the default serializer.

http://www.codeproject.com/KB/XML/GameCatalog.aspx

Probably just a problem with your example, not your real code: Don't use public fields but properties. I think XmlSerializer doesn't even serialize public fields.

like image 139
CodesInChaos Avatar answered Dec 05 '25 14:12

CodesInChaos


Add [XmlIgnore] to the TheShop property to prevent it from being serialized.

You can then set it manually when deserializing.

like image 43
SLaks Avatar answered Dec 05 '25 14:12

SLaks



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!