How is IEnumerable stored in memory in C #?

Like Array is a sequential memory allocation and a list can be stored in memory just like a linked list (please correct me if I'm wrong). How is IEnumerable stored in memory in C #? Suppose I have a class

 public class Employee
 {
      public int Id { get; set; }
      public string Name { get; set; }
 }

      

How memory allocation will differ in two cases. why the compiler won't let us edit IEnumerables

IList<Employee> EmpList ;

Or

IEnumerables<Employee> EmpList ;

      

+3


source to share


3 answers


The variable IEnumerable stores an object reference (which, as an implementation detail, is four or eight bytes depending on the process). The same goes for a System.Collections.Generic.List variable, an array variable, an ICollection variable, or (albeit irrelevant) any reference type variable.

The data generated by the object enumerator will be preserved, but dictated by the object to which the checkpoints belong. In some cases, it will only store the first element along with some information used by the enumerator to compute subsequent elements (for example, System.Linq.Enumerable.Range). In other cases, the object can be an array or an SCGList (sequential stores - lists use arrays to store them) or a linked list or a hash set or a sorted set (which uses a hash table and binary tree, respectively), or just about something that someone wants to dream and realize.

In your question about memory allocation, there is no difference in memory usage between

IList<Employee> empList = new List<Employee>();

      



and

IEnumerable<Employee> empList = new List<Employee>();

      

The difference between the two is in the methods you can call on an object from an empList object reference. In the first case, you are limited to the many members defined in the IList and the interfaces from which it inherits, so you can mutate the collection. In the second case, you can only call GetEnumerator, so you cannot mutate the collection.

+3


source


This question cannot be answered.

It depends on the underlying object that is implementing IEnumerable

.



It could be an array, in which case the memory representation is just an array, or it could be a lazily implemented enumerator that produces values ​​on demand, in which case it doesn't really have a memory representation other than the local state machine variables in that method.

+6


source


IEnumerable

is just an interface, all it has to do is

http://msdn.microsoft.com/en-us/library/cc317868.aspx

to provide a counter:

 public IEnumerator GetEnumerator() 

      

The counter implementation can be different, in fact, it may not be data storage at all:

  // Generates 0, 1, 2, ... sequence
  public sealed class Sample: IEnumerable {
    public IEnumerator GetEnumerator() {
      for(int i = 0;; ++i)
        yield return i;
    }  
  }

      

+2


source







All Articles