Find datatype of Structure fields

Kane Jeeves

Active member
Joined
May 17, 2006
Messages
44
Programming Experience
5-10
I have a simple structure, say
Structure layout
Dim X as String
Dim Y as Integer
End Structure

I want to use Reflection to get the datatype of the fields. I know I can do something like below to get the field, but I can't seem to get the datatype of the field.

Dim valObj As System.Reflection.FieldInfo
valObj = GetType(layout).GetField("X")

I thought using GetTypeCode on valObj would work but it just returns System.Object, not System.String (or Int32) as I'd expect.

Any help is appreciated!

- Kane
 
This returns System.String for me.

VB.NET:
Imports System
Imports System.Reflection

Structure layout
    Dim X As String
    Dim Y As Integer
End Structure

Public Class Form1
    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Dim fi As FieldInfo = GetType(layout).GetField("X")
        Label1.Text = fi.FieldType.ToString()
    End Sub
End Class

Thank you JohnH for the correction it is fi.FieldType.ToString() not fi.ToString()
 
Last edited:
FieldInfo.FieldType property returns the data Type object.
 
Well shucks...

I must've tried every combination except that. Thanks!

So now I can use Type.GetTypeCode(myFieldType) to get the TypeCode. In my actual structure one of the fields is Nullable (Of Integer). How do I get a handle to that?

Basically, I'm writing a value from one structure to another, don't know the names of the structure fields at design time, so as a validity check I want to make sure the data types match between the two structure fields.

Thanks again!

Kane
 
VB.NET:
Structure layout
    Dim X As String
    Dim Y As Nullable(Of Integer)
End Structure

fi.FieldType.ToString() returns "System.Nullable`1[System.Int32]"
 
Nullable (Of Integer). How do I get a handle to that?
Not sure if I understand the question. You compare types with the Is operator, If Type1 Is Type2 Then they're same type...
If you meant to check if value of some type may fit within some Nullable type you can use the Type.GetGenericArguments method.
TypeCode will only tell primitive types, everything else is "Object".
 
Back
Top