Reputation: 44
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
Upvotes: 0
Views: 1053
Reputation: 18013
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:
Upvotes: 1
Reputation: 12849
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.
Upvotes: 1