C#C
C#3y ago
34 replies
krixsick

❔ Interfaces, IEnumerator and IEnumerable

Hello! I just started learning about these topics today and from looking at answers and explanations of these terms I am even more confused. So far, for interfaces I understand that there are like classes that cannot be used to create objects but force other classes to have their methods or fields contained in them. For IEnumerator and IEnumerable, i'm just completely lost. I think im a little dumb but I understand that this is basically explains how the foreach functions by turning our
foreach (var item in something)
into something else that the compiler turns our code into. The IEnumerator has two functions of like movenext() and current and the ienumerable calls a method (GetEnumerator()) which gives an IEnumerator? So in brief, my two questions are this:

1. I was wondering when we would actually use interfaces compared to just adding another method under a class or using a switch case or other functions. I know that interfaces is kind of a work around for the non-existent multi-inheritance which doesn't exist in C# but I can't figure out a good reason for them.
2. How does the IEnumerator and IEnumerable works because I see that you also have to implement this piece of code as well.
image.png
Was this page helpful?