Getting the type of a class property?

  • Thread starter Thread starter Jeff Bunting
  • Start date Start date
J

Jeff Bunting

I'm trying to create a datatable based on the properties of a class. I've
got this

Dim DT As New DataTable
Dim t As Type = Me.GetType
Dim ObjectMembers As MemberInfo() = t.GetProperties
Dim Iterator As MemberInfo

For Each Iterator In ObjectMembers
ColName = Iterator.Name.ToString
ColType = Iterator.GetType
myNewCol = New DataColumn(ColName, ColType)
DT.Columns.Add(myNewCol)
Next


ColType = Iterator.GetType isn't correct though. I want to get the type of
the class property but this is giving me the type of Iterator. I've tried
several variations but haven't hit on the proper syntax. Can someone help
please?

Jeff
 
Hi,

Maybe this will help.

Dim T As Type = Me.GetType

Dim mi As MemberInfo

For Each mi In T.GetProperties

Debug.WriteLine(mi.Name)

Next



Ken
 
Thanks, but I already have the property names (ColName =
Iterator.Name.ToString)

I'm trying to find out the type each property expects (Integer, String,
etc.)

Jeff
 
Hi Jeff,

You will need to use further derived types than MemberInfo, such as FieldInfo or
PropertyInfo. Eg:
Select Case mi.MemberType
Case MemberTypes.Field
returnType = Ctype(mi, FieldInfo).fieldType.Tostring

etc.

that is, you cast your MemberInfo to the FieldInfo or PropertyInfo type, then
get the appropriate member of that.

Bill.
 
Thanks, PropertyInfo rather than MemberInfo was what I needed to use. Makes
it much simpler that way:

Dim t As Type = Me.GetType
Dim ObjectMembers As PropertyInfo() = t.GetProperties
Dim Iterator As PropertyInfo

For Each Iterator In ObjectMembers
ColName = Iterator.Name.ToString
ColType = Iterator.PropertyType
myNewCol = New DataColumn(ColName, ColType)
DT.Columns.Add(myNewCol)
Next

Jeff
 
Back
Top