4

Is this a bad idea? Does calling a generic private constructor within a public constructor create multiple instances, or is this a valid way of initializing class variables?

Private Class MyClass
    Dim _msg As String

    Sub New(ByVal name As String)
        Me.New()
        'Do stuff
    End Sub

    Sub New(ByVal name As String, ByVal age As Integer)
        Me.New()
        'Do stuff
    End Sub

    Private Sub New() 'Initializer constructor
        Me._msg = "Hello StackOverflow"
        'Initialize other variables
    End Sub
End Class
1

3 Answers 3

4

That's perfectly valid and a commonly used way to reuse constructor code. Only one object is instantiated.

Sign up to request clarification or add additional context in comments.

Comments

2

It is a valid approach. There are some caveats with where the new function can be called:

The Sub New constructor can run only once when a class is created. It cannot be called explicitly anywhere other than in the first line of code of another constructor from either the same class or from a derived class.

Read more about the object lifetime on MSDN.

1 Comment

Most thorough answer and thanks for the link. Love reading documentation :) ... (not sarcasm :P)
1

Chaining constructors like this will certainly not create additional object instances.

It is desirable to only write code for a certain portion of initialization once. This is a common and valid initialization pattern.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.