Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Purpose of IDictionary interface

What is the need of IDictionary interface. How can IDictionary interface be initialized. After all it is just an interface. The following code snippet is from msdn. I could not understand it.

IDictionary<string, string> openWith = new Dictionary<string, string>();
like image 320
softwarematter Avatar asked Nov 28 '22 19:11

softwarematter


2 Answers

It defines the important functions that an Dictionary should implement.

The line from MSDN means that you are creating an object openWith which implements the functions (methods) defined in IDictionary interface.

When you use Dictionary to declare the variable like:

Dictionary<string,string> openWith=.....;

you are bind with the concrete type of object. But when you use

IDictionary<string,string> openWith=....;

you can use it with any object that implements IDictionary interface, maybe your own custom class :)

like image 191
TheVillageIdiot Avatar answered Dec 16 '22 15:12

TheVillageIdiot


The whole point of interfaces is to provide... well, an interface to whatever module (I use "module" in a broad sense here) so that calling code will not have to worry about how this particular interface is implemented.

As for "How can IDictionary interface be initialized", this is technically not correct. What can be initialized is a variable, whose type is IDictionary<T, V>. Sure enough variables have to be initialized, but that's usually hidden from the "client code".

IDictionary is not very representative, however. Rather, consider an IDataReader interface. You've surely dealt with ADO.NET, so this should look familiar:

public Foo PopulateFromDataReader(SqlDataReader dataReader)

This particular method is tightly coupled to an SqlDataReader, so you'd have to rewrite it for it to support, say, Access or Oracle or MySQL or Firebird or whatever. In other words, you depend on implementation.

Now consider:

public Foo PopulateFromDataReader(IDataReader dataReader)

This method can be used with whatever class that implements IDataReader, which means with basically any ADO.NET-compatible data provider.

like image 34
Anton Gogolev Avatar answered Dec 16 '22 15:12

Anton Gogolev