For each instance of the *Collection class ( HtmlNodeCollection , TreeNodeCollection , CookieCollection , etc.) that I need to pass to a method that only accepts an array or list (shouldn't have a method that accepts a TreeNodeCollection in a TreeView , for example?) I need to write a method extensions as follows:
public static TreeNode[] ToArray(this TreeNodeCollection nodes) { TreeNode[] arr = new TreeNode[nodes.Count]; nodes.CopyTo(arr, 0); return arr; }
Or loop through the entire collection, adding items to the output list, and then converting the output list to an array:
public static TreeNode[] ToArray(this TreeNodeCollection nodes) { var output = new List<TreeNode>(); foreach (TreeNode node in nodes) output.Nodes(node); return output.ToArray(); }
So my question is: I often need these extension methods. It can allocate a lot of memory if the list is large, as usual. Why can't I get a link (and not a copy) to the internal array used by these *Collection classes so that I do not need to use these extensions and perform these memory allocations? or even provide a ToArray() method. We do not need to know its internal implementation or array used in the latter case.
source share