none
Generic List RRS feed

  • Question

  • Where do the elements save in generic List? I mean is there any array in the class List<T> ?

    Thanks in advance!

    Wednesday, November 14, 2012 3:15 PM

Answers

All replies

  • "I mean is there any array in the class List<T> ?"

    Indeed, a List<T> contains an array of T and the count of elements stored (because the array length can be greater than the count of stored elements). Basically it looks something like this:

    class List<T> {
        private T[] elements;
        private int count;
        ...
    }

    • Marked as answer by Annie1993 Wednesday, November 14, 2012 4:10 PM
    Wednesday, November 14, 2012 3:31 PM
    Moderator
  • Thanks, and how do we change the size of an array T[] elements when we Add elements to List collection ? 
    Wednesday, November 14, 2012 3:34 PM
  • Here is an example of how to resize the array when items are added to Array,

    http://www.tangiblesoftwaresolutions.com/Articles/CSharp%20Equivalent%20to%20VB%20ReDim%20Preserve.html

    But, .NET List is more optimized than the example you see in above link.


    Please mark this post as answer if it solved your problem. Happy Programming!

    • Marked as answer by Annie1993 Wednesday, November 14, 2012 4:10 PM
    Wednesday, November 14, 2012 3:52 PM
  • Thank you!
    Wednesday, November 14, 2012 4:10 PM
  • It's worth adding that List<T> and pretty much other collections that use arrays internally will double the size of the array instead of increasing it by 1 when they need space. Increasing the size by 1 can be very inefficient and should only be done in very specific circumstances.

    Wednesday, November 14, 2012 4:25 PM
    Moderator
  • Yes, thanks!
    Wednesday, November 14, 2012 4:32 PM