Saturday, April 19, 2008

Get\Set Property at runtime

One of my recent tasks has required me to set value of a property at runtime.

VB.Net
Imports System.Reflection

Public Readonly property MyObject as Object
'Use the MyAssembly property created in previous post but make sure you are not using ReflectionOnlyLoad method
Get Dim assy as assembly = MyAssembly
Dim obj as Object = assy.CreateInstance("MyClassName")
return obj
End Get
End Property

Public ReadOnly Property MyPropertyInfo(ByVal propName as String,obj as Object) as PropertyInfo
Get Dim pinfo as PropertyInfo = Nothing
If not obj is Nothing Then
Dim types() as Type = Type.EmptyTypes
pinfo = obj.GetType.GetProperty(propName,types)
End If
return pinfo
End Get

Public property MyProperty as Object
Get
Dim obj as Object = MyObject
Dim value as Object = Nothing
'Get the property of the Object
Dim pinfo as PropertyInfo = MyPropertyInfo("MyPropertyName",obj)
'Do we have a object and the information about the property?
If Not obj Is Nothing AndAlso Not pinfo Is Nothing Then
'Get the value of property
value = pinfo.GetValue(obj,Nothing)
End If
Return value
End Get
Set(ByVal value as Object)
Dim obj as Object = MyObject
Dim pinfo as PropertyInfo = MyPropertyInfo("MyPropertyName",obj)
If Not obj is Nothing AndAlso Not pinfo is Nothing Then
'Get the type of the property
Dim proptype as Type = pinfo.Type
'Is the value a string?
If TypeOf Value is String then
'Depending on the property type cast the value to appropriate Type
Select Case true
Case TypeOf proptype is Boolean
value = Convert.ToBoolean(value)
Case TypeOf proptype is Date
value = Convert.ToDateTime(value)
Case TypeOf proptype is Integer
value = Convert.ToInt32(value)
Case TypeOf proptype is Single
value = Convert.ToSingle(value)
Case TypeOf proptype is Double
value = Convert.ToDouble(value)
Case proptype.IsEnum
value = Enum.Parse(proptype,Value.ToString())
End Select
pinfo.SetValue(obj,Value,Nothing)
End Set
End Property


That was a generic way of getting/setting any property of any class at the runtime. I have used "MyClassName" and "MyPropertyName" for creating an instance of object and getting the property information but that could be replaced by whatever class and whichever property of that class you want to retrieve. If you don't pass empty types while retrieving property info it might give you ambiguous match found exception. If you have 2 properties in your class, one without any parameter and the other one with a parameter, at runtime in absence of Emptytypes it would get confused which property you want to retrieve if you want to access property without the parameter.

No comments:

 
Google