xpo-3266-query-and-shape-data-custom-collection-types.md
Sometimes it is necessary to derive custom collection types from the standard XPCollection or the XPCollection<T>. The standard types have a special constructor that is used when they must be initialized as relationship collections. This specific collection constructor is relevant in two ways:
So, assuming you had a derived collection class MyCollection<T>:
public class MyCollection<T> : XPCollection<T> {
// ...
public MyCollection(Session session, object theOwner, XPMemberInfo refProperty) :
base(session, theOwner, refProperty) { }
// ...
}
Public Class MyCollection(Of T)
Inherits XPCollection(Of T)
' ...
Public Sub New(ByVal session As Session, ByVal theOwner As Object, ByVal refProperty As XPMemberInfo)
MyBase.New(session, theOwner, refProperty)
End Sub
' ...
End Class
To use this collection type in a relation property, use the following code:
public class Album : XPObject {
// ...
}
public class Artist : XPObject {
// ...
MyCollection<Album> myCollection;
[Association("Artist-Albums")]
public MyCollection<Album> Albums {
get {
if (myCollection == null)
myCollection = new MyCollection<Album>(Session, this,
ClassInfo.GetMember(nameof(Albums)));
return myCollection;
}
}
// ...
}
Public Class Album
Inherits XPObject
' ...
End Class
Public Class Artist
Inherits XPObject
' ...
Private myCollection As MyCollection(Of Album)
<Association("Artist-Albums")> _
Public ReadOnly Property Albums() As MyCollection(Of Album)
Get
If myCollection Is Nothing Then
myCollection = New MyCollection(Of Album)(Session, Me, ClassInfo.GetMember(NameOf(Albums)))
End If
Return myCollection
End Get
End Property
' ...
End Class
The code in the property getter is identical to that in the GetCollection<T> method - but because that method doesn’t return our own collection type, we have to replace it.
See Also