Using reflection to instantiate a nested property

  • Thread starter Thread starter MbProgstar
  • Start date Start date
M

MbProgstar

Guest
Hello, I have a problem with instantiating an object by reflection if the object is a nested property. Here is how my class does look like:

Public Class root
Public Property Printing() As rootPrinting
End Class

Public Class rootPrinting
Public Property Printer() As String
Public Property PrinterBatch() As String
End Class



To set the property I have defined a function:

Public Sub SetProperty(ByVal target As Object, ByVal compoundProperty As String, ByVal value As Object)
Dim properties As String() = compoundProperty.Split("."c)
For i As Integer = 0 To properties.Length - 1 - 1
Dim propertyToGet As PropertyInfo = target.[GetType]().GetProperty(properties(i))
target = propertyToGet.GetValue(target, Nothing)
if IsNothing(target) then
if propertyToGet.PropertyType.IsClass then
target = Activator.CreateInstance(propertyToGet.PropertyType)
End If
End If
Next

Dim propertyToSet As PropertyInfo = target.[GetType]().GetProperty(properties.Last())
propertyToSet.SetValue(target, value, Nothing)
End Sub



Thus, in my example I call it like this:

Dim configObject as New root
SetProperty(configObject , "Printing.Printer","Test Printer")



Now, the problem with the above code is that for configObject, the property Printing is not instantiated. If I instantiate it before calling the SetProperty function, then everything is ok:

Dim configObject as New root
configObject.Printing = new rootPrinting()
SetProperty(configObject , "Printing.Printer","skjfkd")

But if not, then the reference object configObject.Printing will be Nothing after executing the function. If the code is debugged then it shows that after executing


target = Activator.CreateInstance(propertyToGet.PropertyType)


the reference to the main object is lost. Although target gets an instantiated object, but the original object remains Nothing.

What have I change in my code?

Continue reading...
 
Back
Top