Good afternoon,
I'm currently reading the Pro ASP.net MVC 4 book published by Apress, and Im on the section which talks about extension methods.
I'm struggling to understand a section of code as follows:
public class ShoppingCart : IEnumerable<Product>
{
public List<Product> Products { get; set; }
public IEnumerator<Product> GetEnumerator()
{
return Products.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
I understand that the ShoppingCart class inherits a product IEnumerable. I understand that we have created a method that returns an Enumerator of Product. I do not understand the final method, IEnumerator IEnumerable.GetEnumerator(). Can someone please enlighten me in 'newbie' terms?
Thanks
The last method you have to implement
IEnumerator IEnumerable.GetEnumerator()
is a heritage of ancient .Net versions when .Net doesn't support generics (and IEnumerator<T>
). Since then, every IEnumerable<T>
for compability reasons should not only implement
IEnumerator<T> GetEnumerator()
But old style non-generic
IEnumerator GetEnumerator()
as well. You can see it just from the declaration
public interface IEnumerable<out T> : IEnumerable {...}
http://msdn.microsoft.com/en-us/library/9eekhta0(v=vs.110).aspx
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments