Click here to Skip to main content
15,905,071 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
How to create private constructor in vb.net? and
how to use?Please Explain?
Posted
Updated 26-Sep-15 3:40am
v2
Comments
Afzaal Ahmad Zeeshan 26-Sep-15 9:55am    
A constructor that is private to the class itself, the one that cannot be called by external objects (classes). You cannot use it, because it is available in the class only.

As the name implies a private constructor is a constructor having the access level defined as private. This means that (in most of the scenarios) an instance of the class cannot be created outside the class using this constructor. For information about access level definitions, have a look at Access Levels in Visual Basic[^]

A typical scenario is a singleton where you want to have a single instance of a non-static class. This means that once the instance is created all code is using the same instance of the class. An implementation could look like
VB
Public Class Singleton
   Private Shared ReadOnly TheInstance As Singleton = New Singleton()

   Private Sub New()
   End Sub

   Public Shared ReadOnly Property Instance As Singleton
      Get
         Return TheInstance
      End Get
   End Property
End Class

And the usage like
VB
Dim a As Singleton = Singleton.Instance
Dim b As Singleton = Singleton.Instance

Of course there are other scenarios where a private constructor can be used. For example if you want to define a class and force the usage of a parameter (or parameters) during the construction then you can hide the default constructor by making it private. Consider the following class
VB
Public Class ForcedParameterization

   Private Sub New()
   End Sub

   Public Sub New(somevalue As Integer)

   End Sub
End Class

And the usage
VB
Dim c As ForcedParameterization = New ForcedParameterization() 'Causes an error: Overload resolution failed because no accessible 'New' accepts this number of arguments.
Dim d As ForcedParameterization = New ForcedParameterization(5) ' compiles just fine
 
Share this answer
 
v2
Comments
CPallini 26-Sep-15 10:04am    
5.
Wendelius 26-Sep-15 11:32am    
Thanks :)
tharif4me 26-Sep-15 11:56am    
thanks...bro
Wendelius 27-Sep-15 3:30am    
You're welcome :)
Maciej Los 26-Sep-15 12:45pm    
5ed!
In addition to solution 1 by Mika Wendelius[^], i'd suggest to read the documentation:
Creating Classes in Visual Basic .NET[^]
Constructor Design[^]
9.3 Constructors[^] - follow the links on the bottom of resulting page
Constructor Usage Guidelines[^]
Using Constructors and Destructors[^]
 
Share this answer
 
Comments
Wendelius 27-Sep-15 3:30am    
Good links
Maciej Los 27-Sep-15 6:36am    
Thank you, Mika.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900