tags:

views:

40

answers:

3

What is the diference of using interfaces like ...

I have an interface

Public Interface IProDataSource

    Function read() As Integer

End Interface

Then a class

Public Class DataSource : Implements IProDataSource

     Function read() As Integer Implements IProDataSource.read

         some code...

     End Function

End Class

Then I use this the next way ... but what is the difference? ... boths approaches are working ...

Dim obj As IProDataSource = New DataSource
obj.read()

vs

Dim datas as new Datasource
datas.read()

The only difference I have notice is that if the method is declare private it will be visible using the first approach only.

Thanks for any comments !!!

+1  A: 

If obj is a DataSource, you cannot get to the non-Interface methods of the DataSource through a variable declared as the interface. Otherwise, in your example, there is really no difference.

Notice the "is a".

IList is a good interface to check out. Many objects take or use IList as method parameters. (To see all the classes that implement IList, open the "Object Browser", browse to IList and expand "Derived Types".) For example, if I was implementing a Windows.Forms control, instead of forcing you to pass a list as an Array, List, Collection, or some other object, I could specify IList and any class that implements that interface can be used by the control.

A practical example, the DataSource property of a ComboBox accepts any object that implements the System.Collections.IList interface, such as a System.Data.DataSet or an System.Array.

Interfaces Overview

Interfaces, like classes, define a set of properties, methods, and events. But unlike classes, interfaces do not provide implementation. They are implemented by classes, and defined as separate entities from classes.

An interface represents a contract, in that a class that implements an interface must implement every aspect of that interface exactly as it is defined.

http://msdn.microsoft.com/en-us/library/s3et34z3(VS.80).aspx

AMissico
A: 

At the moment is seems like using the interface is a waste of effort...

But what happens if tomorrow you, or omebody else, decides to write an XMLDatasource, or a CSVDatasource, or an InternetDataSource.

If you implement your applicatino using the first way ( Dim obj as IProDataSource) then you don't need to care what kind of datasource is being used. As long as whaterver DataSource implements the interface, your program will work with it.

IF you use the second method (Dim datas as new DataSource) then when I try to use my SuperFancyDataSource with your program, you'll have to go through your whole program and change all of the New DataSources to New SuperFanceDataSource.

Michael Rodrigues
A: 

See this question from a friend of mine:

Why is an interface or an abstract class useful? (or for what?)

Venemo