Public Class SampleClass
Private myName As String
Private myAge As Integer = 99
'constructor with optional parameter
Public Sub New(ByVal name As String, Optional ByVal age As Integer = 0)
myName = name
If age <> 0 Then
myAge = age
End If
End Sub
End Class
Public Class SampleClass
'the same result with constructor overloading example
Private myName As String
Private myAge As Integer = 99
Public Sub New(ByVal name As String)
myName = name
End Sub
Public Sub New(ByVal name As String, ByVal age As Integer)
myName = name
myAge = age
End Sub
End Class
What about neseted invocations?
'Nested constructors example
Public Class SampleClass
Private myName As String
Private myAge As Integer
Public Sub New(ByVal name As String)
Me.New(name, 99)
End Sub
Public Sub New(ByVal name As String, ByVal age As Integer)
myName = name
myAge = age
End Sub
End Class
Is it just a matter of coders flawor, or does it depend more on situation (if yes, where is first example of better use than the second)?
The last thing I'd like some opinion are private constructors. What are your thoughts, comparing those lines with previous two examples:
'Private constructors example
Public Class SampleClass
Private myName As String
Private myAge As Integer
Private Sub New()
myName = "Default Name"
myAge = 99
End Sub
Public Sub New(ByVal name As String)
Me.New()
Me.myName = name
End Sub
Public Sub New(ByVal age As Integer)
Me.New()
Me.myAge = age
End Sub
End Class
In addition, what about the usage of object initializers?
'Object initializer example
Public Class SampleClass
Public Name As String
Public Age As Integer
'... other class stuff
End Class
Private Sub InitializeClassInstance()
Dim myClassInstance As New SampleClass With {.Name = "lucky3", . Age = 696 ' ;-)
End Sub
In general, I'd like to hear opinions for when one usage is more sutable than the other, or are those just different ways to the same goal, and are really just coding style dependant.
This post has been edited by lucky3: 27 August 2012 - 04:49 AM

New Topic/Question
Reply


MultiQuote


|