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 ;
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With