wavedrop
wavedrop

Reputation: 530

VB.NET - Automatically initialize extended property of type Object

I am building a code behind page that has a public property (MyDTOItem) which is essentially a DTO object (dtDTOItem) Note: In my code the Get and Set are actually real code (I stripped it for the example).

The problem I am having is in the Page_Load event. When I set the .Member1 property of the DTO object the Get code runs and not the Set and therefore the DTO ibject property .Member1 never gets assigned.

I figured out that if I add code (MyDTOItem = New dtDTOItem) to the Page_Load event then it will set the value correctly. What I am trying to figure out is how to initialize the property object without having to do it explicitly. It has to be an extended property because I have custom Get and Set code.

Thank you in advance.

Public Property MyDTOItem As dtDTOItem
    Get

    End Get
    Set(value As dtDTOItem)

    End Set
 End Property


<DataContract(), Serializable()> _
Public Class dtDTOItem

  <DataMember()> _
  Property Member1 As String = ""

  <DataMember()> _
  Property Member2 As String = ""

  <DataMember()> _
  Property Member3 As String = ""

End Class


Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    MyDTOItem.Member1 = "temp string"
End Sub

Upvotes: 1

Views: 1878

Answers (1)

Sam Axe
Sam Axe

Reputation: 33738

You must instantiate the field that backs your MyDTOItem property before attempting to set property values on it. You don't get to cheat and not instatiate an object before you start messing with its members.

Example:

Private oBackingField As SomeObject = New SomeObject

Public Property VisibleProperty As SomeObject Get

End Get .... etc.

No events involved. Well.. it probably works out to the Init or PreInit event.. but you dont have to worry your pretty little head about that.

EDIT 2

Prior to .NET 4 you had to craft all your properties with backing fields, and even still to this day if you provide property accessors you must provide your own backing field... it looked like this:

Private backingField As DataType = New DataType  ' Create backing field and initialize it

Public Property forwardFacingProperty As DataType
Get
  Return backingField
End Get
Set (byval tValue as DataType)
  backingField = tValue
End Set
End Property

Upvotes: 1

Related Questions