Elad Benda
Elad Benda

Reputation: 36656

Why use IList over IEnumerable?

1) I read some (general) code snippet and saw some places that used IList<T> and some used IEnumerable. What is the pros to use the first over the latter?

2) is and as in c#. I understand is does type check and as does casting. But what is exactly casting? forcing data to some sized object? when is and as differ?

Upvotes: 15

Views: 1983

Answers (2)

Marc Gravell
Marc Gravell

Reputation: 1062512

A IList[<T>] represents something that:

  • can be iterated
  • is of finite, known size
  • is repeatable
  • can be accessed randomly by index
  • can (optionally, checkable) be edited: reassign values, add, remove, etc

An IEnumerable, on the other hand, can only be iterated. Not all things that can be iterated are lists. For example:

static IEnumerable<int> Get() {
    Random rand = new Random();
    while(true) yield return rand.Next();
}

that ^^^ is an infinite sequence. It has no length, cannot be mutated, cannot be accessed by index... however, it can be iterated:

foreach(int i in Get().Take(200)) {
    Console.WriteLine(i);
}

is performs a type check that returns true/false... i.e. is obj an IList? yes or no.

as performs a "try to do this" type-check; it returns null if it fails, or a typed reference (etc) if it is successful. Basically, it is an efficiency thing:

if(obj is IList) {
    var list = (IList) obj;
    ...
}

is less efficient than:

var list = obj as IList;
if(list != null) {
    ...
}

they also behave differently if obj is null; is throws an exception; as returns null.

Upvotes: 29

Femaref
Femaref

Reputation: 61427

  1. IList offers certain methods that IEnumerable doesn't. Most importantly, the ability to add to it (for more information, check out the msdn)
  2. is compares types, returning if a certain object can be casted to a type. as actually performs that cast, returning null if it failed. Casting means converting an object of type A to an object of type B, for whatever reason.

Upvotes: 3

Related Questions