PDA

Click to See Complete Forum and Search --> : [2.0] Need to retrieve Private Array from another class


MasterEvilAce
Aug 10th, 2006, 02:00 AM
I have two classes

Class 1 has a List of objects that's PRIVATE. I currently have two functions to add and delete from the list. I need a way to retrieve all the objects in the list.. either by using a function to RETURN the list so I can access it on Class 2, or some other magical way. Hopefuly there's a way to do it without making the list public?

jmcilhinney
Aug 10th, 2006, 02:14 AM
The standard way would be to use a Private variable and a Public ReadOnly property. That's how just about every collection property in the Framework is structured. That way you can get a reference to the collection from outside so you can get the items and modify the collection but you cannot assign a whole new collection in its place:Private myField As ArrayList

Public ReadOnly Property MyProperty() As ArrayList
Get
If Me.myField Is Nothing Then
Me.myField = New ArrayList
End If

Return Me.myField
End Get
End PropertyIf you don't want the caller to be able to modify the collection then you should return an array containing the items instead of a reference to the collection:Private myField As ArrayList

Public ReadOnly Property MyProperty() As Object()
Get
If Me.myField Is Nothing Then
Me.myField = New ArrayList
End If

Return Me.myField.ToArray()
End Get
End PropertyNote that this creates a completely new array object each time the property is accessed so it should be done as infrequently as possible.

jmcilhinney
Aug 10th, 2006, 02:18 AM
Ooops. Sprecken zie VB? :blush:private ArrayList myField;

public ArrayList MyProperty
{
get
{
if (this.myField == null)
{
this.myField = new ArrayList();
}

return this.myField;
}
}private ArrayList myField;

public object[] MyProperty
{
get
{
if (this.myField == null)
{
this.myField = new ArrayList();
}

return this.myField.ToArray();
}
}

MasterEvilAce
Aug 11th, 2006, 06:49 PM
Just what i needed, thanks a lot!