CollectionBase inheritance problem

  • Thread starter Thread starter Jeremy
  • Start date Start date
J

Jeremy

I am creating a custom collection. Very simple.

Imports System.Collections

Public Class ShapesCollection
Inherits BaseCollection

Default Public Property Item(ByVal index As Integer) As Shape
Get
Return CType(List(index), Shape)
End Get
Set(ByVal Value As Shape)
List(index) = Value
End Set
End Property

Public Function Add(ByVal value As Shape) As Integer
MsgBox(value Is Nothing)
MsgBox(list Is Nothing)

Return List.Add(value)
End Function

End Class

My client code looks like this:

Public Class frmDraw
Inherits System.Windows.Forms.Form

Dim m_Shapes As ShapesCollection
Dim rand As New Random
Dim m_PanelGraphics As Graphics

....code snipped for brevity

Private Sub frmDraw_Load(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MyBase.Load
cboColors.Text = "Black"
m_Shapes = New ShapesCollection
m_PanelGraphics = Panel1.CreateGraphics
End Sub

Private Sub cmdCircle_Click(ByVal sender As Object, ByVal e As
System.EventArgs) Handles cmdCircle.Click

m_Shapes.Add(New Circle(rand.Next(50, 200), rand.Next(10,
300), rand.Next(10, 50), Color.FromName(cboColors.Text)))
RefreshScreen()

End Sub

....code snipped for brevity

End Class

When I run this, I get a NullReferenceException in the Add method of
my custom collection. The first msgbox pops up False, and the Second
pops up
True. This means the List property of the BaseCollection class is
Nothing.
How can this be??? I would think the base class would be smart enough
to
initialize its own variables.
 
Jeremy,
As Brian suggested, Inherit from System.Collection.CollectionBase.

It appears that you inadvertently inherited from
System.Windows.Forms.BaseCollection.

The BaseCollection.List property is overridable requiring you to override it
and supply an ArrayList.

The CollectionBase.List property is not overridable, as CollectionBase
supplies & maintains the ArrayList for you.

Hope this helps
Jay
 
Back
Top