views:

50

answers:

1

Is there a way for a property to access its own name and type at runtime using reflection? I want to access this info without hard coding the name or index of the property in the class.

Simple Example Code:

Private ReadOnly Property MyProperyName() As String
    Get
        Console.WriteLine((Get Current Property Info).Type.ToString)
        Console.WriteLine((Get Current Property Info).Name)
        Return ""
    End Get
End Property

Expected output:

System.String
MyPropertyName
+2  A: 

You can use a StackTrace to get the current method:

Dim currentMethod = CType(new StackTrace(0, false).GetFrame(0).GetMethod(), _ 
    System.Reflection.MethodInfo)

If you can assume that you're in a property, then you can strip the "get_" off of the front of the method name:

Dim propertyName as string = currentMethod.Name.SubString(4)

And use ReturnType for the property type:

Dim propertyType as Type = currentMethod.ReturnType
Adam Robinson
Very nice Thanks!
Tim Santeford