Recent Posts

Tuesday, February 24, 2009

How to overload Constructor in vb.net

Constructors are the initialisation code of the classes or the objects that we use in Visual Basic .NET or in Visual Studio C#.NET or in Visual Basic.
In this short explanation I have used VB .NET code to explain how we can overload the constructor or have multiple constructors that can accept different parameters. Overloading helps to pass multiple paramaters to a method without using optional keyword in the method. If you overload the constructor of a class in visual basic or in c# .NET, you can initialize values for the properties of the class and which can later used in the class for performing various tasks.

Please look below where I have used the ConnectMe class where I have two constructors one has got string passed to it the other one doesn't have any parameter passed to it.

Here I have used the external connection string in one constructor to instantiate the connection string but in other constructor, if I don't get the connection string then I call the function ReadDatabaseConfig which in turn gets me the connection String.

By below example we can easily explain the use of overloading the constructor.



Public Class ConnectMe

    Public connStr As String = "" 

    Public Sub New(ByVal strConn As String)
        
        connStr = strConn
        If Not Connect() Then
            Exit Sub
        End If
    End Sub

    Public Sub New()

        ReadDatabseConfig(strDBConfFile)
        If Not Connect() Then
            Exit Sub
        End If
    End Sub

End Class

Related Posts by Categories




No comments:

Post a Comment