I have a class called Primes and this class implements GetEnumerator() without implementing IEnumerable interface.
public class Primes
{
private long min;
private long max;
public Primes()
: this(2, 100)
{
}
public IEnumerator GetEnumerator()
{...}
I don’t get it. Am I missing something?
Firstly, as others have said you can introduce your own methods without implementing interfaces anyway – you can write your own
Disposemethod without implementingIDisposableetc. For well-known interfaces I’d suggest this is almost a bad idea (as readers will have certain expectations) but it’s entirely valid.More importantly though, the
foreachstatement in C# can work withoutIEnumerablebeing involved. The compiler effectively does compile-time duck typing on the namesGetEnumerator(),CurrentandMoveNext(). This was primarily to allow strongly-typed (and non-boxing) iteration in C# 1, before generics. See section 8.8.4 of the C# 3 spec for more details.However, it’s generally a bad idea to do this now if you do want to be able to easily iterate over the contents of an instance as a collection – and indeed I’d suggest implementing
IEnumerable<T>instead of justIEnumerable.