Using Constructors with Object Oriented Database Development with VB.NET 2005 - Constructor overloading within a class
(Page 3 of 5 )
I already defined method overloading in my previous articles. If you are new to the concept, I suggest you go through my previous articles. Now, we shall examine constructor overloading within a class:
Public Class Emp
Private m_empno As String
Private m_ename As String
Private m_sal As Double
Private m_deptno As Integer
Private m_errMsg As String
Public Sub New()
m_empno = ""
m_ename = ""
m_sal = 0
m_deptno = 0
m_errMsg = ""
End Sub
Public Sub New(ByVal empno As String, ByVal ename As String, ByVal sal As
Double, ByVal deptno As Integer)
m_empno = empno
m_ename = ename
m_sal = sal
m_deptno = deptno
m_errMsg = ""
End Sub
...
End Class
From the above, we understand that there exist two constructors, constructors without any parameter (or default constructor) and constructors with parameters. We can also include constructors accepting objects as parameters as follows:
Public Sub New(ByVal objEmp As Emp)
m_empno = objEmp.empno
m_ename = objEmp.ename
m_sal = objEmp.sal
m_deptno = objEmp.deptno
m_errMsg = ""
End Sub
Adding one more method to retrieve a connection string
You must have observed that I hard coded connection strings everywhere when working with database connections. It is always a bad practice to hard code connection strings within an application. I suggest you place the connection string in an XML based "config" file and read it when necessary. This concept is a bit beyond the scope of this article.
You can temporarily add a private method, "getConnectionString," to the same class which returns the database connection string. You can use this method everywhere whenever you open the database connections. The following is a simple template for the same:
Private Function getConnectionString() As String
Return "Data Source=.sql2k5;initial catalog=sample;user
id=sa;password=eXpress2005"
End Function
If you are trying to read a "config" file for the connection string, try to include the logic for the same in the above method. Later you can use the above method for creating database connections as follows:
Dim cn As New SqlConnection(getConnectionString())
You can define your own class to store all your settings in the form of a "config" file. The next section will give you the complete code for working with a "config" file. The source code mainly deals with an XML based "config" file. It automatically creates a new "config" file, if it does not exist.
The code mainly uses the concept of serialization to store and load the XML data available within the "config" file.
Next: The complete source code for working with the config file >>
More Visual Basic.NET Articles
More By Jagadish Chaterjee