That is the slick part about interfaces. You can define a variable of type
"some interface" - and then instantiate it with ANY class that implements
that interface. With the example I gave before.. Imagine you have an
IDataAccess interface that defines ways that you can get data - and includes
login and logout. Now imagine I have 3 classes "WebSvcAccess", "SQLServer"
and "OfflineAccess" that all implement that interface.
Let me stress the signifigance of this.
The ENTIRE application is written to the IDataAccess interface, it has NO
IDEA what those other classes are - and at RUN-time, the user chooses thier
access type. So long as those classes have correctly implemented the
interface - the whole app runs the same no matter what the connection type.
So one time, I do this:
IDataAccess objMainAccessObject = new WebSvcsAccess();
-or-
IDataAccess objMainAccessObject = new SQLServer();
-or-
IDataAccess objMainAccessObject = new OfflineAccess();
And it is ONLY at that time that my application knows what kind of access
they will be using. After that, the method of data access is *completely*
abstracted. This is basically the "factory" design pattern (more or less).
The whole rest of the app just interacts with objMainAccessObject as if it
was the same all along. And in theory, you could even switch access types -
like if you went from offline access to being plugged into the net. you
could freeze the app, re-instantiate objMainAccessObject with new
SQLServer() and pick up where you left off. It's really a hugely powerful
concept.
So you aren't creating an instance of an interface (because you can't) - but
you can define a variable to be of an interfaces "type", and then
instantiate it with an object that implements that interface.. this alone is
such a GREAT feature of OO that you just couldn't do in VB6.. or that you
could do in C++, but you could also easily work around this. It seems much
easier to enforce this in a real strongly-typed environment like this...
Stan said:
Nice to see this thread appear as I have my own interface based query to put
to the group. I was just reading up on an article that has some sample code
and was perplexed to see this line appear,
ICodeCompiler loCompiler = new CSharpCodeProvider().CreateCompiler();
I believe this is similar to a sample that someone else has posted to this
thread. What confuses me is the fact that you are able to create an instance
of type interface. I would have thought that you would have to create a type
of something which implements the interface, since the interface defines
only exposed methods i.e. no implementation and doesn't even define
constructors. What is the base type of the instance in this case? Is it
simply an System.object type which is obliged to support the interface? I'm
thinking that must be it. I think this is different to specifying an
interface as a function argument, in which case we are saying that whatever
is passed must support the interface.