Visual Basic Private Constructor

In visual basic, Private Constructor is a special instance constructor and it is useful in a classes that contain only static members. If a class contains one or more private constructors and no public constructors, then the other classes are not allowed to create an instance for that particular class except nested classes.

Visual Basic Private Constructor Syntax

Following is the syntax of defining a private constructor in visual basic programming language.

 

Class User

    ' Private Constructor

    Private Sub New()

        ' Custom Code

    End Sub

End Class

If you observe the above syntax, we created a private constructor without having any parameters that means it will prevent an automatic generation of default constructor. In case, if we didn’t use any access modifier to define constructor, then by default it will treat it as a private.

Visual Basic Private Constructor Example

Following is the example of creating a private constructor in visual basic programming language to prevent other classes to create an instance of particular class.

 

Module Module1

    Class User

        ' Private Constructor

        Private Sub New()

            Console.WriteLine("I am Private Constructor")

        End Sub

        Public Shared name, location As String

        ' Default Constructor

        Public Sub New(ByVal a As String, ByVal b As String)

            name = a

            location = b

        End Sub

    End Class

    Sub Main()

        ' The following comment line will throw an error because constructor is inaccessible

        ' Dim user As User = New User()

 

        ' Only Default constructor with parameters will invoke

        Dim user1 As User = New User("Suresh Dasari", "Hyderabad")

        Console.WriteLine(User.name & ", " & User.location)

        Console.WriteLine("Press Enter Key to Exit..")

        Console.ReadLine()

    End Sub

End Module

If you observe the above example, we created a class with private constructor and default constructor with parameters. If we uncomment the commented line (Dim user1 As User = New User()), it will throw an error because the constructor is private so it won’t allow you to create an instance for that class.

 

Here, we are accessing the class properties directly with a class name because those are static properties so it won’t allow you to access with instance name.

 

When we execute above the visual basic program, we will get the result like as shown below.

 

Visual Basic Private Constructor Example Result

 

This is how we can use private constructor in visual basic programming language to prevent creating an instance of particular class based on our requirements.