July 21, 2003

SetProperty – Setting a property via reflection

‘ Set a property via reflection and return True if successful’ Example: SetProperty(Button1, “Text”, “Click me”)Function SetProperty(ByVal obj As Object, ByVal propertyName As String, _ ByVal val As Object) As Boolean Try ‘ get a reference to the PropertyInfo, exit if no property with that ‘ name Dim pi As

GetProperty – Reading a property via reflection

‘ Read a property via reflection or return a default value’ Example: MessageBox.Show(GetProperty(Button1, “Text”, “”))Function GetProperty(ByVal obj As Object, ByVal propertyName As String, _ ByVal defaultValue As Object) As Object Try Dim pi As System.Reflection.PropertyInfo = obj.GetType().GetProperty _ (propertyName) If Not pi Is Nothing Then Return pi.GetValue(obj, Nothing) End If

GetField – Retrieving the value of a public field via reflection

‘ Return the value of the public field with the specified name,’ defined inside the obj object’ Note: requires Imports System.Reflection” Example:’ Public TestField As String = “hello”‘ …’ MessageBox.Show(GetField(Me, “TestField”, “”))Function GetField(ByVal obj As Object, ByVal fieldName As String, _ ByVal defaultValue As Object) As Object Try ‘ try

InvokeMethod – Invoking a method via reflection

‘ Invoke a method via reflection and return its result – return null if method ‘ doesn’t exist or throws’ Note: requires Imports System.Reflection” Example:’ Function GetCompleteName(ByVal firstName As String,’ ByVal lastName As String)’ Return lastName & “, ” & firstName’ End Function’ …’ MessageBox.Show(InvokeMethod(Me, “GetCompleteName”, False, “Marco”,’ “Bellinaso”))Function InvokeMethod(ByVal

IsMemberSupported – Check whether an object supports a member with the specified name

‘ Check whether an object supports a member with the specified name” Examples:’ Debug.WriteLine(IsMemberSupported(Button1, “BackColor”)) ‘ => True’ Debug.WriteLine(IsMemberSupported(Button1, “Focus”)) ‘ => True’ Debug.WriteLine(IsMemberSupported(Button1, “TextColor”)) ‘ => False’ Debug.WriteLine(IsMemberSupported(Button1, “Print”)) ‘ => FalseFunction IsMemberSupported(ByVal obj As Object, ByVal memberName As String) As _ Boolean ‘ get the array of MemberInfo