4

Searched in internet for What is IEnumerable interface in C#? The problem it solves? What if we don't use it? But never really did not get much. Lots of posts explain how to implement it.

I've also found the following example

List<string> List = new List<string>();
        List.Add("Sourav");
        List.Add("Ram");
        List.Add("Sachin");

       
        IEnumerable names = from n in List where (n.StartsWith("S")) select n;
        // var names = from n in List where (n.StartsWith("S")) select n;

        foreach (string name in names)
        {
            Console.WriteLine(name);
        }

The above ex outputs:

Sourav

Sachin

I wanted to know, the advantage of using IEnumerable in the above example? I can achieve the same using 'var' (commented line).

I would appreciate if anyone of you can help me out to understand this and whats the benefit of using IEnumerable with an example? What if we don't use it?.

Community
  • 1
  • 1
Maltesh
  • 383
  • 2
  • 6
  • 14
  • `IEnumerable names = ...` means that you are not interested in exact type of the items in the sequence. Anything will be good enough. So, you can write `foreach (int name in names)` and it will compile (but fail at runtime for sure). You can declare the type explicitly: `IEnumerable names = ...` or you can allow the compiler to infer it for you: `var names = ...` – Sinix Dec 19 '14 at 14:09

3 Answers3

7

Beyond reading the documentation I'd describe IEnumerable<T> as a collection of Ts, it can be iterated over and many other functions can be carried out (such as Where(), Any() and Count()) however it's not designed for adding and removing elements. That's a List<T>.

It's useful because it's a fundamental interface for many collections, various data access layers and ORMs use it and many extension methods are automatically included for it.

Many concrete implementations of Lists, Arrays, Bags, Queues, Stacks all implement it allowing a wide variety of collections to use it's extension methods.

Also collections implementing either IEnumerable or IEnumerable can be used in a foreach loop.

From msdn

for each element in an array or an object collection that implements the System.Collections.IEnumerable or System.Collections.Generic.IEnumerable interface.

In your code example you've got a variable called names which will be an IEnumerable<string>, it's important to understand that it will be an IEnumerable<string> regardless of whether you use the var keyword or not. var just allows you to avoid writing the type so explicitly each time.

TLDR

It's a common base interface for many different types of collections which let you use your collection in foreach loops and provides a lot of extra extension methods for free.

Liath
  • 9,913
  • 9
  • 51
  • 81
  • "It's also one way of allowing your collection to be usable in a foreach loop" No its the ONLY way. – Aron Dec 19 '14 at 08:12
  • Whats the benefit of using IEnumerable? Just search the benefit of using interfaces in OOP. – jlvaquero Dec 19 '14 at 08:13
  • @Aron I was sure there was another... maybe I'm thinking of the generic/non-generic version. I've changed to "most common" until I can back it up! – Liath Dec 19 '14 at 08:14
  • What if we don't use it? It is realy hard to not use IEnumerable in .NET even if you don't know you are using it. ;) – jlvaquero Dec 19 '14 at 08:16
  • 1
    @Aron, actually, [it is not](http://msdn.microsoft.com/en-us/library/windows/desktop/9yb8xew9(v=vs.80).aspx). – Sinix Dec 19 '14 at 08:28
2

IEnumerable and much more preferred IEnumerable<T> are the standard way to handle the 'sequence of elements' pattern.

The idea is each type : IEnumerable<T> looks like if there's a label: "ENUMERATE ME". No matter what's there: queue of order items, collection of controls, records from a sql query, xml element subnodes etc etc etc - it's all the same from enumerable's point of view: you've got a sequence and you can do something for each item from the sequence.

Note that IEnumerable is somewhat limited: there's no count, no indexed access, no guarantee for repeatable results, no way to check if enumerable is empty but to get the enumerator and to check if there is anything. The simplicity allows to cover almost all use cases, from collections to ad-hoc sequences (custom iterators, linq queries etc).

The question was asked multiple times, here're some answers: 1, 2, 3

Community
  • 1
  • 1
Sinix
  • 1,306
  • 9
  • 46
1

MSDN

"The disadvantage of omitting IEnumerable and IEnumerator is that the collection class is no longer interoperable with the foreach statements, or equivalent statements, of other common language runtime languages."

So you need to implement this interface so your custom collection type can be used with other CLR languages. It seems like a CLS requirement.

Community
  • 1
  • 1
Mert Akcakaya
  • 3,109
  • 2
  • 31
  • 42