A
A
agoge2015-02-23 11:33:37
ASP.NET
agoge, 2015-02-23 11:33:37

Why is the GetEnumerator() method of the IEnumerable interface implemented twice?

Good afternoon.
Please tell me, I'm trying to figure out an example from the ASP.NET MVC 4 book and in Listing Listing 4-14 there is an incomprehensible moment for me.

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace LanguageFeatures.Models
{
  public class ShoppingCart : IEnumerable<Product>
  {
    public List<Product> Products { get; set; }
    public IEnumerator<Product> GetEnumerator()
    {
      return Products.GetEnumerator();
    }
   IEnumerator IEnumerable.GetEnumerator()
    {
      return GetEnumerator();
    }
  }
}

Why is the GetEnumerator() method of the IEnumerable interface implemented twice?
Thank you very much in advance.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander S, 2015-02-23
@agoge

To answer this question, you need to delve into history. Namely, there was a moment when there was no Generic typing and there was only an untyped IEnumerable enumeration interface. And then, with the advent of the new version of .Net, generics appeared (this is when the type is explicitly specified <T>, in your case the data type <Product>).
The signature of this interface is as follows:
That is, for backward compatibility, the new interface inherits the old one, which means that two methods need to be implemented: one that returns the old untyped version, and a new, more convenient typed version.
For understanding: in the old version, when you looped through each element through foreach, the element type was object (all other types are inherited from it). And at each iteration, in order to get your own Product type and work with it, you had to do type casting.
In the new version, due to the fact that the type is explicitly specified <Product>when traversing in the loop, you immediately get an object of the Product type.
I recommend reading on this topic in general changes in .Net when switching from version to version + reading about Generic in the dotnet.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question