I have a question regarding interfaces. I understood that you cannot create instances of interfaces, right? However I see on a page demonstrating usage of IDictionaryEnumerator interface:
// Loop through all items of a Hashtable
IDictionaryEnumerator en = hshTable.GetEnumerator();
while (en.MoveNext())
{
string str = en.Value.ToString();
}
Isn’t this creating an object named en of type IDictionaryEnumerator? I’ve read about GetEnumerator() in trying to understand what it returns:
Returns a reference to an enumerator
object, which is used to iterate over
a Collection Object.
..but I don’t really understand when should I create such references of interfaces instead of class objects. I mean what is the advantage of doing this.
Thank you in advance.
This is just a demo of polymorphism – The hshTable.GetEnumerator() is returning you a instance that looks to the outside world as IDictionaryEnumerator. This instance can exhibit a different behavior than for example lets say a instance got from myFactory.GetEnumerator(). Both objects look like IDictionaryEnumerator but have different implementations of the methods that the IDictionaryEnumerator interface exposes. Hope it helps.