Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Relation between IEnumerable and arrays

Tags:

c#

.net

What makes .Net IEnumerable so special that compiler types like arrays can be passed as an argument in its place with it being a class library interface. Is there some sort of inheritance in the background?

What actually happens when an array can interchangeably replace a collection or IEnumerable as a parameter:

public void DoJob(IEnumerable<Job> jobs)
{
}

Like this method call:

Job job = new Job();
DoJob(new [] { job });
like image 997
Saleh Avatar asked Dec 09 '25 06:12

Saleh


1 Answers

Since you came from Java, I will start by telling you that in C#, there is a unified type system, where every type derives from object, unlike in Java where there are special "primitives".

So in C#, arrays are just another type. Who says they can't implement interfaces? They can! All the compiler provides is some syntax for creating them. In actuality, arrays' type is System.Array.

This is its declaration:

public abstract class Array : ICloneable, IList, ICollection, 
    IEnumerable, IStructuralComparable, IStructuralEquatable

See IEnumerable in there?

EDIT:

For IEnumerable<T>, we can find it in the language spec:

Section 12.1.2:

A one-dimensional array T[] implements the interface System.Collections.Generic.IList (IList for short) and its base interfaces.

IList<T> implements IEnumerable<T>.

like image 84
Sweeper Avatar answered Dec 11 '25 20:12

Sweeper



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!