Virtual ICollection

1k views Asked by At

In c# is this efficient programming?

I was wondering since t1 links to t2 and t2 links to t1 and hence it also links back to itself will it make it take more space or like is it a dangerous algorithm/code?

static void Main(string[] args)
{
    Test t1 = new Test(1);
    Test t2 = new Test(2);
    Test t3 = new Test(3);
    Test t4 = new Test(4);
    t1.Links = new List<Test>();
    t1.Links.Add(t2);
    t2.Links = new List<Test>();
    t2.Links.Add(t1);

    Console.WriteLine(t1.Links.First().Links.First().id);
    Console.Read();
    return;
}

public class Test
{
    public int id { get; set; }

    public virtual ICollection<Test> Links { get; set; }

    public Test(int Id)
    {
        id = Id;
    }
}

I am using this type of structure in MVC. I have noticed that MVC also loads these virtual objects from the DB along with the main object, So I was wondering if that would be a problem

2

There are 2 answers

0
Euphoric On

The main problem of circular reference between instances is that it makes harder to reason about structure of data while program is running. This causes lots of code to get more complicated as it needs to anticipate and detect possible circular references.

So while there is nothing inherently wrong with your code, you should first think if you REALLY need to have circular reference. There might be other, more cleaner ways to represent your data.

0
György Kőszeg On

If you need circular references just use them logically, it is nothing wrong with them (eg. tree nodes with Children and Parent cause also CRs).

In some cases CRs can be a pain but nothing serious:

  • Serialization: Default binary serialization handles them correctly but may cause to serialize the whole graph regardless of the node you really want to serialize. You might want to use some customization to avoid such problems. Similar considerations can be taken in account by XML, json and other kind of serializations, too.
  • Garbage collection: Your object graph will not be released until at least one node is referenced from somewhere. If you want to release the objects one by one make sure you de-link them correctly on removal, or make them disposable, which removes every reference to the disposed object.