0

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

  • Possible duplicate of [Garbage collector and circular reference](http://stackoverflow.com/questions/8840567/garbage-collector-and-circular-reference) – Ondrej Svejdar Jan 05 '17 at 09:45
  • 2
    What are you trying to archive with that object tree? If your problem requires a data structure with circular references, it is OK to create such a data structure... there is nothing dangerous in it ;) – JanDotNet Jan 05 '17 at 09:45
  • Like @JanDotNet just said, there is nothing bad in it. You could maybe safe time/space by creating a better structure. You could definetly safe one List here... but it really depends what you want to Archive. – Cataklysim Jan 05 '17 at 09:48

2 Answers2

1

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.

Euphoric
  • 12,645
  • 1
  • 30
  • 44
1

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.
György Kőszeg
  • 17,093
  • 6
  • 37
  • 65