pdavila (10) [Avatar] Offline
#1
Erik,

Thanks for the book. It's very good at getting developers up and running very quickly with Windows Forms programming.

In chapter 5, you introduce the CollectionBase class. Since this class inherits from IEnumerable, the CollectionBase class implements the required GetEnumerator. What I don't understand is who is implementing the three members of the IEnumerator interface, i.e., Current, MoveNext and Reset? The GetEnumerator function returns an IEnumerator but not a class that implements the IEnumerator!

Thanks,

Peter
eebrown (89) [Avatar] Offline
#2
Re: Implementation for IEnumartor interface in Chapter 5 (Collection Base)
Peter,

The GetEnumerator function returns an object that implements the IEnumerator interface. One of the nice things about interfaces is you don't care what that object actually is.

Practically, I believe the CollectionBase class has an internal private class that implements the IEnumerator interface. So the class can create an instance of this class and return it as an IEnumerator instance. You have no idea what this class is, but it is still there.

You could probably use Reflection on the object to figure out exactly what the class is called and where it comes from, but this would be a longer discussion.

Glad you're enjoying the book. My publisher tells me to encourage readers to post on Amazon or elsewhere when they actually like the text, so consider yourself encouraged.

Erik
pdavila (10) [Avatar] Offline
#3
Re: Implementation for IEnumartor interface in Chapter 5 (Collection Base)
Erik,

Thanks for the response.

Let me see if I understand this now. Is it fair to say that anytime the .NET framework returns some interface from a method or property, it is really returning an object that implements that interface? For example, the List property of the CollectionBase class returns an IList. Isn't true then that what it is really returning is an object that implements the IList interface?

The way that I understand this now is that it must be so because an interface can not be instantiated. We can only instantiate an object that implements an interface. Are my assumptions above correct? Are there any examples in the framework where this is not so. That is, any example where the framework would return the interface and not object that implements the interface?

Thanks,

Peter
eebrown (89) [Avatar] Offline
#4
Re: Implementation for IEnumartor interface in Chapter 5 (Collection Base)
Peter,

Yes, I think you have it. In C#, any instance of anything is an object, interface or otherwise. But interfaces do not define logic or constructors, only the "shell" of what the interface is capable of performing.

So there is always some underlying object that implements that interface, even if it isn't apparent.

Erik