Property problem. Please, need some help on this.

  • Thread starter Thread starter shapper
  • Start date Start date
S

shapper

Hello,

I created a user control (.ascx) with a property as follows:

Private _Messages As Generic.List(Of String)
Public Property Messages() As Generic.List(Of String)
Get
Return _Messages
End Get
Set(ByVal value As Generic.List(Of String))
_Messages = value
End Set
End Property ' Messages

I then use the following code in MyPage.aspx.vb where I use this
control:

' MyUserControl_Init
Private Sub MyUserControl_Init(ByVal sender As Object, ByVal e As
EventArgs) Handles MyUserControl.Init

With MyUserControl.Messages
.Add("Message 01")
.Add("Message 02")
End With

End Sub ' MyUserControl_Init

I get the error:

Exception Details: System.NullReferenceException: Object reference not
set to an instance of an object.

Any idea why?

I really don't know what I am doing wrong.

Thanks,

Miguel
 
Hi there,

You're exposing a reference to the list that has not been instantiated. For
this type of property (internal instance of a list) you must create an
instance and expose it through readonly property, otherwise you allow callers
to change instance whilst you want to change list content only (add or remove
items)

Private _Messages As Generic.List(Of String) = new Generic.List(Of String)()
Public Readonly Property Messages() As Generic.List(Of String)
Get
Return _Messages
End Get
End Property


or "lazy" initialization:

Private _Messages As Generic.List(Of String) = nothing
Public Readonly Property Messages() As Generic.List(Of String)
Get
if _Messages is nothing then
_Messages = new Generic.List(Of String)()
end if
Return _Messages
End Get



Hope this helps
 
Back
Top