0

I was wondering if there was an object/function that works like XmlSerializer does - but that does not require the Serializable Attribute to be set.

Here's why: I have a third party object that I would like to extract the information in the public properties (including any collections).

And - of course - the following routine returns an error of:

There was an error reflecting type 'ThridPartyObject' 

because the object was not compiled with the [Serializable] attribute.

Public Sub SerialMe(ThridPartyObject as Object)
    Dim objStreamWriter As New StreamWriter("C:\Object.xml")
    Dim x As New XmlSerializer(ThridPartyObject.GetType)
    x.Serialize(objStreamWriter, ThridPartyObject)
    objStreamWriter.Close()
End Sub

Perhaps something that would iterate through all the public properties of the 3rd party object? (And the public properties of those properties - and so on)

Any ideas?

Scott Savage
  • 373
  • 1
  • 4
  • 17
  • I assume you tried reflection because of the error message you posted. i.e. http://stackoverflow.com/questions/1196991/get-property-value-from-string-using-reflection-in-c-sharp – djv Jul 02 '14 at 20:24
  • No. I haven't rolled my own code to do this yet. Didn't want to reinvent the wheel if something else was out there. The Error above was returned by the XmlSerializer object. – Scott Savage Jul 02 '14 at 20:35
  • Well if it's not marked [Serializable] I'd suspect that it's not serializable :). Reflection should work – djv Jul 02 '14 at 21:01
  • did the reflection idea work you you? – djv Jul 03 '14 at 15:23

1 Answers1

0

You can use reflection to access properties and fields by string name

Imports System.Reflection

Module Module1
    Sub Main()
        Dim c1 As New class1 With {.prop1 = 6, .field1 = 7}
        Console.WriteLine(c1.GetType().GetProperty("prop1").GetValue(c1, Nothing))
        Console.WriteLine(c1.GetType().GetField("field1").GetValue(c1))
    End Sub
End Module

Class class1
    Public Property prop1 As Integer
    Public field1 As Integer
End Class
djv
  • 15,168
  • 7
  • 48
  • 72