Level Extreme platform
Subscription
Corporate profile
Products & Services
Support
Legal
Français
Class referencing itself
Message
From
14/03/2018 03:22:38
 
General information
Forum:
C#
Category:
Class design
Miscellaneous
Thread ID:
01658720
Message ID:
01658731
Views:
44
This message has been marked as a message which has helped to the initial question of the thread.
>Hi everybody,
>
>I just found we have a class that has List property of itself. I never saw such implementation before - is it valid (OK) in C#? That extra property is defined as the following:
>
>
>[JsonProperty("nodes", NullValueHandling = NullValueHandling.Ignore)]
>        public List<EditItDraftViewModel> Nodes { get; set; }
>        public EditItDraftViewModel()
>        {
>            //Initialize the collection.
>            Nodes = new List<EditItDraftViewModel>();
>        }
>
>When this class is used in the following code:
>
>
>private List<EditItDraftViewModel> NestItemTrees(int parentId, List<ItDrafts> flatList, 
>            Dictionary<int,int> childNodeCounts)
>        {
>            var subs = flatList.Where(f => f.ParentId == parentId).ToList();
>            var nOut = new List<EditItDraftViewModel>();
>            if (subs != null && subs.Count > 0)
>            {
>                foreach (var sub in subs)
>                {
>                    var subVm = AutoMapperConfig.Mapper.Map<ItDrafts, EditItDraftViewModel>(sub);
>                    int ct = 0;
>                    childNodeCounts.TryGetValue(subVm.NodeId, out ct);
>                    subVm.InitChildNodeCount = ct;
>
>                    subVm.Nodes = NestItemTrees(subVm.NodeId, flatList,childNodeCounts);  //Recursively nest SubNodes
>                    nOut.Add(subVm);
>                }
>            }
>            return nOut.Count > 0 ? nOut : null;
>        }
>
>I'm getting StackOverflow exception on the var sumVm line.
>
>All this code was written by my colleague and I am just trying to understand it and prevent the error from happening.
>
>I did a quick Google Search and found https://stackoverflow.com/questions/37251043/automapper-throwing-stackoverflowexception-when-calling-projecttot-on-iquery
>
>So, should I try to add MaxDepth for the above call?
>
>Is it OK to have a class referencing itself (it's a recursive tree)?
>
>Thanks in advance.

Nothing wrong, in principle, with a class containing a list of it's own instances but if, as you discovered, if it recursively passes an instance that has already been processed you will end up in an infinite loop.
Either, as you mentioned, limit the recursion count or, maybe better depending on the expected structure, check that an item has not already been processed.
Previous
Next
Reply
Map
View

Click here to load this message in the networking platform