nish91
nish91

Reputation: 143

IEnumerator vs IEnumerator<T>

I'm fairly new to c sharp and was looking for an answer to the following:

Why would you want to implement IEnumerator<T> when you have IEnumerator? IEnumerator returns back the item from the collection as type object, so caters for all types.

Thanks

Upvotes: 2

Views: 1037

Answers (1)

Eric Lippert
Eric Lippert

Reputation: 660038

[The non-genericized] IEnumerator returns back the item from the collection as type object, so caters for all types.

That's exactly the problem. You now know nothing about the objects that are in the sequence. They could be anything and so you have to be able to deal with anything coming out of that sequence. If you have a sequence of giraffes, or a sequence of customers, or a sequence of integers, then you know that every element in the sequence will be a giraffe, customer, integer, whatever. If you have a sequence of objects then you have to write code that checks what kind of thing each of those objects is.

Having type information enables the compiler to thread that information through the system. Suppose we have an IEnumerable<Customer>. So everything in the sequence is a customer. If we then say:

var first = customers.First();
var address = first.Address;

Now the compiler can deduce that first is a Customer, and know that customers have addresses, and so the second line is legal. If customers were just IEnumerable then the compiler cannot prove that your program is typesafe!

Also, some types exhibit a performance penalty called the "boxing penalty" when treated as object. Having a generically-typed collection eliminates that penalty.

Upvotes: 11

Related Questions