tags:

views:

167

answers:

5

Will anyone describe IEnumerable and what is difference between IEnumerable and array and where to use it.. all information about it and how to use it.

+7  A: 

An array is a collection of objects with a set size.

int[] array = [0, 1, 2];

This makes it very useful in situations where you may want to access an item in a particular spot in the collection since the location in memory of each element is already known

array[1];

Also, the size of the array can be calculated quickly.

IEnumerable, on the other hand, basically says that given a start position it is possible to get the next value. One example of this may be an infinite series of numbers:

public IEnumerable<int> Infinite()
{
    int i = 0;
    while(true)
        yield return i++;
}

Unlike an array an enumerable collection can be any size and it is possible to create the elements as they are required, rather than upfront, this allows for powerful constructs and is used extensively by LINQ to facilitate complex queries.

//This line won't do anything until you actually enumerate the created variable
IEnumerable<int> firstTenOddNumbers = Infinite().Where(x => x % 2 == 1).Take(10);

However the only way to get a specific element is to start at the beginning and enumerate through to the one you want. This will be considerably more expensive than getting the element from a pre-generated array.

Of course you can enumerate through an array, so an array implements the IEnumerable interface.

Martin Harris
+1 Thorough answer... even though 2147483647 is hardly infinite. ;)
djacobson
@djacobson It *is* infinite, it just isn't contiguous. The next value is -2147483648... :)
Martin Harris
+2  A: 

An Array is a collection of data. It's implied that the items are store contiguously, and are directly addessable.

IEnumerable is a description of a collection of data. They aren't collections themselves. Specifically, it means that the collection can be stepped through, one item at a time.

IF you define a varaible as type IEnumerable, then it can reference a collection of any type that fits that description.

Arrays are Enumerable. So are Lists, Dictionaries, Sets and other collection types. Also, things which don't appear to be collection can be Enumerable, such as a string (which is IEnumerable<char>), or or the object returned by Enumerable.Range(), which generates a new item for each step without ever actually holding it anywhere.

James Curran
+1  A: 

One thing is that Arrays allow random access to some fixed size content. Where the IEnumerable interface provides the data sequentially, which you can pull from the IEnumerable one at a time until the data source is exhausted.

Chris Taylor
A: 

.NET has its IEnumerable interface misnamed - it should be IIterable. Basically a System.Collection.IEnumerable or (since generics) System.Collection.Generic.IEnumerable allows you to use foreach on the object implementing these interfaces.

(Side note: actually .NET is using duck typing for foreach, so you are not required to implement these interfaces - it's enough if you provide the suitable method implementations.)

An array (System.Array) is a type of a sequence (where by sequence I mean an iterable data structure, i.e. anything that implements IEnumerable), with some important differences.

For example, an IEnumerable can be - and is often - lazy-loaded. That means that until you explicitly iterate over it, the items won't be created. This can lead to strange behaviour if you're not aware of it. As a consequence, an IEnumerable has no means of telling you how many items it contains until you actually iterate over it (which the Count extension method in System.Linq.Enumerable class does).

An array has a Length property, and with this we have arrived to the most important difference: an array if a sequence of fixed (and known) items. It also provides an indexer, so you can conveniently access its items without actually iterating over it.

And just for the record, the "real" enumerations in .NET are types defined with the enum keyword. They allow you express a choices without using magic numbers or strings. They can be also used as flags, when marked with the FlagsAttribute.

I suggest you to use your favioure search engine to get more details about these concepts - my brief summary clearly doesn't aim to provide a deep insight to these features.

ShdNx
The terminology used in .Net is perfectly fine. From http://en.wikipedia.org/wiki/Enumeration: "In mathematics and theoretical computer science, the broadest and most abstract definition of an enumeration of a set is an exact listing of all of its elements". What you call "real" enumerations are more properly known as "enumerated types": http://en.wikipedia.org/wiki/Enumerated_type
Gabe
A: 

Arrays

A .Net array is a collection of multiple values stored consecutively in memory. Individual elements in an array can be randomly accessed by index (and doing that is quite efficient). Important members of an array are:

  • this[Int32 index] (indexing operator)
  • Length

C# has built-in support for arrays and they can be initialized directly from code:

var array = new[] { 1, 2, 3, 4 };

Arrays can also be multidimensional and implement several interfaces including IEnumerable<T> (where T is the element type of the array).

IEnumerable<T>

The IEnumerable<T> interface defines the method GetEnumerator() but that method is rarely used directly. Instead the foreach loop is used to iterate through the enumeration:

IEnumerable<T> enumerable = ...;
foreach (T element in enumerable)
  ...

If the enumeration is done over an array or a list all the elements in the enumeration exists during the enumeration but it is also possible to enumerate elements that are created on the fly. The yield return construct is very useful for this.

It is possible to create an array from an enumeration:

var array = enumerable.ToArray();

This will get all elements from the enumeration and store them consecutively in a single array.

To sum it up:

  • Arrays are collection of elements that can be randomly accessed by index
  • Enumerations are abstraction over a collection of elements that can be accessed one after the other in a forward moving manner
Martin Liversage