Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use IList over IEnumerable?

Tags:

c#

.net

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?

like image 318
Elad Benda Avatar asked Nov 05 '11 22:11

Elad Benda


Video Answer


2 Answers

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.

like image 89
Marc Gravell Avatar answered Sep 18 '22 17:09

Marc Gravell


  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.
like image 24
Femaref Avatar answered Sep 21 '22 17:09

Femaref