Getting and Setting properties on runtime using Reflectoion
In series of Reflection related posting this is the second post. You can see the post here. Now I am posting about Properties. We can set / read properties of Class using reflection.
Setting Properties
1) For setting properties, we enumerate all the properties using Type.GetProperties() method
2) Then we will check, whether the property is readonly or not.
3) Read the value(if the datatype of property and the datatype of the value you are trying to set, didn’t match it will throw some error.)
4) If datatype is mismatching, convert the value to property data type using “Convert.ChangeType” *
5) Call the PropertyInfo.SetValue method.
Here is the source code, here I am reading from Registry and Loads the required data in a class level variable.
Dim result As MyCustomClass Dim PropertyValue As Object Dim converter As New TypeConverter For Each CurrentProperty As PropertyInfo In MyType.GetProperties If CurrentProperty.CanWrite Then PropertyValue = GetValue(CurrentProperty.Name) 'GetValue function retuns the value based on the parameter given. If PropertyValue IsNot Nothing Then CurrentProperty.SetValue(result, Convert.ChangeType(PropertyValue, CurrentProperty.PropertyType), Nothing) End If End If Next
* Convert.ChangeType – Works only with basic datatypes.
And for getting we will do almost reverse operation.
Getting values from Property
It is simple and strait forward, and here is the code
Dim propertyValue As String For Each CurrentProperty As PropertyInfo In MyType.GetProperties If CurrentProperty.CanRead Then propertyValue = CurrentProperty.GetValue(MyCustomClass, Nothing).ToString End If Next
Happy Reflection.
