Calling a Private Constructor

BrainSlugs83

Member
Joined
Feb 1, 2007
Messages
5
Location
Seattle
Programming Experience
10+
I'm developing a class library in VB.NET.

One of my classes I do not want foreign code to be able to create an instance of, but the class must be public as another class will expose a public member which will be an instance of this class. That's a mouthful. An example of this type of behavior can be seen in "System.Drawing.Imaging.ColorPalette" -- it cannot be created. But if you "Dim bmp As New System.Drawing.Bitmap(1, 1, Imaging.PixelFormat.Format8bppIndexed)" then "bmp.Palette" will be a new instance of a "System.Drawing.Imaging.ColorPalette".

I want to do kind of the same thing with a class in my class library; How can I accomplish this?
 
I think you may use a Friend function which returns the instance.

Hi,
I think you may use a Friend Function which returns the instance of the class which has the Private Constructor.



'For example, These two classes can be in ClassLibrary1.
VB.NET:
'Class which is using a private constructor.
Public Class Class1 'Similar to Palette??

    Private strVariable As String

    'Private constructor.
    Private Sub New()
        strVariable = "Private Constructor called!"
    End Sub

    Public Sub CallMe()
        Console.WriteLine(Me.strVariable)
    End Sub

    'Friend Function to return the instance of this class.
    Friend Shared Function GetInstance() As Class1
        Return New Class1
    End Function

End Class

Public Class Class2 'Similar to Bitmap??

    Private _Class1 As Class1

    Public Sub New()
        Me._Class1 = Class1.GetInstance() 'Returns instance of the class with private constructor.
    End Sub

    Public ReadOnly Property Clas1()
        Get
            Return Me._Class1
        End Get
    End Property

End Class

The below code will be using the above classes.

VB.NET:
Imports ClassLibrary1

Module Module1

    Sub Main()
        Dim c1 As Class1
        Dim c2 As New Class2 'Similar to Bitmap class, I think
        c1 = c2.Clas1 'Similar to bmp.Palette
        c1.CallMe()
        Console.ReadLine()
    End Sub

End Module
 
Thanks, actually, through experimenting, I found out that I could just make the constructor "Friend", ex "Friend Sub New" -- I only knew about private and public before, (Never made a class library before, so Friend always acted like public to me and I never knew what it did.)
 
Back
Top