Amc_rtty
Amc_rtty

Reputation: 3803

referencing an interface

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.

Upvotes: 2

Views: 213

Answers (3)

supercat
supercat

Reputation: 81143

A variable of an object type can be thought of as holding an "object id". The only things that can be done directly with an object ID are to assign it to another object ID, or compare it against another object ID. Saying someObject.foo effectively says "take the object referred to by the object ID in variable "someObject", and use the "foo" method on it.

An interface may be thought of as an extra connection panel which is attached to an object, with a set of standardized set of connections. If a variable is declared to be of an interface type, it will hold the ID of an object which has such a panel, and saying "someInterface.foo" says to use the "foo" method of the panel (which will in turn be connected to--and activate--some method within the object itself).

Note that for an interface to be usable, its outside connections have to be wired to something on the inside. To instantiate just an interface would be to make a panel with nothing connected to it. There would be no way for any methods performed on the interface to have any effect, since there would be no wired-in implementation for any of them.

Upvotes: 1

OpenSource
OpenSource

Reputation: 2257

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.

Upvotes: 3

vc 74
vc 74

Reputation: 38179

The code creates an instance of a class that implements the interface

One class can implement several interfaces and several classes can implement the same interface

By using an interface, you are less dependent on a specific implementation but just to an interface (contract)

Upvotes: 2

Related Questions