I got stuck with Adam Freeman "Asp net" book, I read a lot about IEnumerable and IEnumerator interface, but it's still hard to understand some results. I have these two classes.
public class ShoppingCart : IEnumerable<Product>
{
public IEnumerable<Product> Products { get; set; }
public IEnumerator<Product> GetEnumerator()
{
return Products.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
and an extension of the first one,
public static class MyExtensionMethods
{
public static decimal TotalPrices (this IEnumerable<Product> products)
{
decimal total = 0;
foreach (Product prod in products)
{
total += prod?.Price ?? 0;
}
return total;
}
}
Product is an easy class with some fields like Name, Price etc. I have lot of doubts. First of all I don't understand how c# knows MyExtensionMethods is an extension of ShoppingCart, then I don't understand how can TotalPrices know that prod come from Products in ShoppingCart class. Could someone explain me briefly the logic behind these few lines?
Thank you everyone, sorry for the dumb question.