Level Extreme platform
Subscription
Corporate profile
Products & Services
Support
Legal
Français
Class referencing itself
Message
 
 
To
All
General information
Forum:
C#
Category:
Class design
Title:
Class referencing itself
Miscellaneous
Thread ID:
01658720
Message ID:
01658720
Views:
41
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.
If it's not broken, fix it until it is.


My Blog
Next
Reply
Map
View

Click here to load this message in the networking platform