Property problem. Please, need some help on this.

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
 
G

Guest

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,995
Messages
2,570,236
Members
46,821
Latest member
AleidaSchi

Latest Threads

Top