Interface called without implementing all methods

T

tshad

I am a little confused here.

I was under the impression that before you can use an interface (and you
can't instantiate an interface), you have to implement all the methods.

But I am trying to set up a Generic DataBase class and this seems to work.
I am not instantiating the IDbConnection interface and am not defining any
of the methods (ChangeDatabase, Close, CreateCommand, Open).

In the following I am defining dbConn as an IDbConnection and am passing it
back as an IDbConnection type:
********************************************************************
Sub LoadGrid3()
Dim dbConn As IDbConnection = _
GetConnection("Persist Security Info=False;Data Source=AW;Initial
Catalog=Inter")
Dim dbCmd As SqlCommand = New SqlCommand("GetUsers", dbConn)
dbCmd.CommandType = CommandType.StoredProcedure

dbCmd.Parameters.Add("@UserID",SqlDBType.Int).value = 1
dbConn.Open()

DataGrid1.DataSource = dbCmd.ExecuteReader
DataGrid1.DataBind()
End Sub

Function GetConnection(ConnectString As String) As IDbConnection
Dim cnn As New SqlConnection(ConnectString)
return cnn
End Function
**************************************************************************

Why does this work????

Thanks,

Tom
 
J

Jacques

I'm not so sure about the first part of your post, but with regards to the
part about "Why does this work?"... It's because your method 'GetConnection'
is instantiating a SqlConnection object and passing that back to the caller.
In other words your function is not actually returning an IDbConnection, but
rather an instance of a SqlConnection object.

Hope it helps
Jacques
 
B

Barrie Wilson

tshad said:
I am a little confused here.

I was under the impression that before you can use an interface (and you
can't instantiate an interface), you have to implement all the methods.

you're not "calling an interface" as your Subject suggests; you're declaring
dbConn as being of type IDbConnection and you will get no complaint from the
compiler on this. If, on the other hand, you create a new class and
implement IDbConnection

class newClass : IDbConnection

you *must* implement all the members in the interface.

Importantly, notice that SqlConnection DOES implement all of the members of
interface IDbConnection. Accordingly, when you pass dbConn around to a
method expecting an IDbConnection type, you're ok.

I'm not clear why you need to declare dbConn as type IDbConnection here but
perhaps you have reasons to do so.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,013
Latest member
KatriceSwa

Latest Threads

Top