1

I have a collection of data models that have associations with other models, and the data schema is often circular in nature. I want to create C# classes to represent this data objects, but it'll result in circular references.

Here is a simple example

 class ClassA {
     public ClassB parent;
 }

 class ClassB {
     public ClassA child;
 }

When these two classes are instantiated with a circular reference to each other. Will C# leak memory? How will the garbage collector know to release these?

I remember in Java there was a feature that allowed you to define a class member as having a weak reference. Does C# have something like that?

Reactgular
  • 52,335
  • 19
  • 158
  • 208
  • 1
    There is a [WeakReference](http://msdn.microsoft.com/en-us/library/system.weakreference.aspx) class, not sure if you need to use it though - possibly the GC would be smart enough to clean up anyway.. – Blorgbeard May 20 '13 at 01:32
  • 3
    The GC doesn't use reference counting. If you have a set of circularly-referenced objects, they will be GCed if they aren't reachable from the roots (stack variables and static members, basically). – siride May 20 '13 at 01:33

0 Answers0