How to find out all properties name and data type

  • Thread starter Thread starter Eric Shi
  • Start date Start date
E

Eric Shi

Hi,

I am using VB.Net. During the runtime, can I find out
all the property names and their types for an object so I
can access them. For example, if objectA has propertyA
and PropertyB, I would like to do something like
For each Property in ObjectA
messagebox.show convert.tostring(property.Name)
messagebox.show convert.tostring(property.value)
messagebox.show convert.tostring(property.DateType)
Next

Thanks

Eric Shi
 
Eric,

Try the System.Reflection Namespace for what you need.

Here's a simple example of how to list the public propeties of an object:
(Watch out for line breaks)

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Module Module1

Sub Main()
' Variables
Dim objTest As Person = New Person()
Dim aProperties() As System.Reflection.PropertyInfo
Dim objProperty As System.Reflection.PropertyInfo

' Gets array of properties on the object
aProperties = objTest.GetType.GetProperties

' Loop through each property, printing it's name and type
For Each objProperty In aProperties


Console.WriteLine("Property Name: " & objProperty.Name _
& "; Type: " & objProperty.PropertyType.Name _
& "; Value: " & objProperty.GetValue(objTest,
Nothing).ToString)

Next

End Sub
End Module

' Simple class to demonstrate reflection
Public Class Person

Private mName As String
Public Property Name() As String
Get
Return mName
End Get
Set(ByVal Value As String)
mName = Value
End Set
End Property

Private mAge As Integer
Public Property Age() As Integer
Get
Return mAge
End Get
Set(ByVal Value As Integer)
mAge = Value
End Set
End Property

End Class

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

You can get pretty much any information about the objects you are dealing
with (including Private fields etc.) Beware though, powerful as reflection
is, it shouldn't be used as a shortcut around good object design. What
you're doing sounds suspiciously like late binding which has various
drawbacks like performance and allowing run time errors to creep in.

Hope this helps,

Trev.
 
Eric Shi said:
I am using VB.Net. During the runtime, can I find out
all the property names and their types for an object so I
can access them. For example, if objectA has propertyA
and PropertyB, I would like to do something like

\\\
Imports System.Reflection
..
..
..
Dim pi() As PropertyInfo = Me.GetType().GetProperties()
Dim p As PropertyInfo
For Each p In pi
MsgBox(p.Name)
Next m
///
 
Back
Top