Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How IEnumerable are stored in memory in c#?

Like Array is the sequential memory allocation, and list might get stored in memory in the same way as linked list ( please correct me if i am wrong ). How IEnumerable are stored in memory in c#? Suppose I have a class

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

How the memory allocation will differ in below two cases. why compiler doesn't allow us to edit IEnumerables

IList<Employee> EmpList ;

Or

IEnumerables<Employee> EmpList ;
like image 320
Shivang MIttal Avatar asked Sep 11 '14 06:09

Shivang MIttal


2 Answers

This question is impossible to answer.

It depends on the underlying object that implements IEnumerable.

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

like image 160
Lasse V. Karlsen Avatar answered Sep 18 '22 08:09

Lasse V. Karlsen


An IEnumerable variable stores an object reference (which, as an implementation detail, will be four or eight bytes, depending on the process). The same is true of a System.Collections.Generic.List variable, an array variable, an ICollection variable, or (although not relevant to the question) any reference-type variable.

The data produced by the object's enumerator will be stored however dictated by the object to which the reference points. In some cases, it will store only the first element along with some information used by the enumerator to calculate subsequent elements (System.Linq.Enumerable.Range, for example). In other cases, the object could be an array or S.C.G.List (sequential storage -- lists use arrays for their storage), or a linked list, or a hash set or sorted set (which use a hash table and binary tree, respectively), or just about anything else someone wants to dream up and implement.

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

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

and

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

The difference between these two is in the methods you can call on the object from the empList object reference. In the first case, you are limited to the many members defined in 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.

like image 37
phoog Avatar answered Sep 20 '22 08:09

phoog