Mikko
Mikko

Reputation: 15

Implementing add method for array-type property in custom class

I'm creating a class called Job with a property called Tasks. Tasks is an array of the type Task (another class). I can return the Tasks collection using a public readonly property that returns the array, but how do I implement an add method to add a task to Tasks?

I started with a simple class and researched Write Own "Add" Method For An Array and Add new item to Object Array and many others. I have an inherent mistake in my thinking and I do not know the right terms to find the correct solution.

Public Class Job
    Private _taskcount As Integer
    Private _tasks() As Task
    Public ReadOnly Property TaskCount
        Get
            Return _taskcount
        End Get
    End Property
    Public ReadOnly Property Tasks As Task()
        Get
            Return tasks
        End Get
    End Property
End Class

I would love to be able to dim myjob as new job and then do myjob.tasks.add, but I do not have an idea where in the class definition the Add method goes. Help with adding the Add method would be greatly appreciated.

Edit: I also understand that the property TaskCount should be implemented as Tasks.Count. So my underlying problem is the implementation of properties and methods of a property.

Upvotes: 0

Views: 206

Answers (1)

djv
djv

Reputation: 15774

Here is a possible way to write your class, guarding your List while exposing it as an IEnumerable

Public Class Job
    Private _tasks As New List(Of Task)
    Public ReadOnly Property TaskCount As Integer
        Get
            Return _tasks.Count
        End Get
    End Property
    Public ReadOnly Property Tasks As IEnumerable(Of Task)
        Get
            Return _tasks
        End Get
    End Property
    Public Sub AddTask(t As Task)
        _tasks.Add(t)
    End Sub
End Class

We don't need to cache the task count since your list has a Count property.

Also I don't see the need to the property TaskCount because you can just get it from myJob.Tasks.Count. The property could [read: should] be removed.

Now, you also mentioned you would like to be able to do Dim myJob As New Job() and then do myJob.Tasks.Add. You could expose the list publicly like below, making Tasks ReadOnly.

Public Class Job
    Public ReadOnly Property Tasks As New List(Of Task)
End Class

Now anyone can do Dim myJob As New Job() and then do myJob.Tasks.Add and since Tasks is ReadOnly nobody can reassign it (I mean NOBODY, even inside the class (outside the constructor!)...). But now you can access all the properties and methods of List

There is no right answer without knowing your specific requirements. But there is a lot of discussion on the topic. See https://stackoverflow.com/a/387973/832052 and https://stackoverflow.com/a/400144/832052

Upvotes: 1

Related Questions