user432209
user432209

Reputation: 20167

Default values of Class properties

I have a class, it looks like this:

Public Class DataPoint
    Private _data As Integer
    Private _locInText As Integer
    Private _searchValue As String

    Property Data As Integer
        Get
            Return _data
        End Get
        Set(value As Integer)
            _data = value
        End Set
    End Property
    Property LocInText As Integer
        Get
            Return _locInText
        End Get
        Set(value As Integer)
            _locInText = value
        End Set
    End Property
    Property SearchValue As String
        Get
            Return _searchValue
        End Get
        Set(value As String)
            _searchValue = value
        End Set
    End Property
End Class

I then create another class using this class.

Public Class PaintData
    Public Time As TimeSpan
    Public Color As DataPoint
    Public Job As New DataPoint
    Public MaxCurrent As New DataPoint
End Class

I want to create default values of some of the properties, namly SearchValue and LocInText. To me, it makes sense to do this inside the class definition, because these are essentially constants.

Q1. Should I be doing it this way? If not, what is the proper technique.

Q2. I can't get the syntax right. Can you help?

Public Class PaintData
    Public Time As TimeSpan
    Public Color As DataPoint
    Public Job As New DataPoint
    Public MaxCurrent As New DataPoint

    Color.LocInText = 4 '<----Declaration expected failure because I'm not in a method
    Job.LocInText = 5 '<----Declaration expected failure because I'm not in a method
End Class

Thanks all

Upvotes: 4

Views: 8573

Answers (1)

James Thorpe
James Thorpe

Reputation: 32192

Give DataPoint a constructor:

Public Class DataPoint
    Private _data As Integer
    Private _locInText As Integer
    Private _searchValue As String

    Public Sub New(locInText as Integer)
        _locInText = locInText
    End Sub

    '...
End Class

And use that:

Public Class PaintData
    Public Time As TimeSpan
    Public Color As New DataPoint(4)
    Public Job As New DataPoint(5)
    Public MaxCurrent As New DataPoint(6)
End Class

Alternatively you could use

Public Property Color As DataPoint = New DataPoint With {.LocInText = 4}

in your class definition. This syntax is arguably more readable than the constructor syntax.

Upvotes: 6

Related Questions