facebook  linkedin  Twitter  skype  Rss googlePlus

Properties, Getting and Setting Them Dynamically

Jan 03 2006

Iterating Through Properties

In this code snippet we have a custom object that contains a method called GetProperties. The purpose of this method is so the object can return an arraylist of all the named properties it contains. Again you could use this to populate a drop down which then adds fields to be reported on or calculated against.

Public Function GetProperties() As ArrayList
   Dim Properties As New ArrayList
   Dim PropertyInfo As PropertyInfo() = Me.GetType.GetProperties()
   Dim PropertyItem As PropertyInfo
   For Each PropertyItem In PropertyInfo
   Return Properties
End Function

You can see we use the PropertyInfo object and then used the method GetProperties. This returns an array type which we can then iterate through and build an arraylist that the object will return containing all the named properties it contains.

Setting the Value of a Named Property

In this next method we provide code on how to set the value of a named property at run time. For example, say we used the previous method to obtain a list of named properties, and now we want to set the value of the property for our object.

Public Sub SetProperty(ByVal PropertyName As String, _
   ByVal PropertyValue As String)
   Dim userType As Type = Me.GetType()
   Dim UserProp As PropertyInfo = userType.GetProperty(PropertyName)
   UserProp.SetValue(Me, PropertyValue, Nothing)
End Sub

As you can see again we use PropertyInfo, get the property of the object and pass the current object which in this example is a custom user object. Then pass the value we want the property to contain.

Get the Value of a Named Property

In the next code block, we'll obtain the value of a named property at runtime for our custom object.

Public Function GetPropertyByNamedValue(ByVal PropertyName As _
   Dim userType As Type = Me.GetType()
   Dim UserProp As PropertyInfo = userType.GetProperty(PropertyName)
   Dim myValue As String
   myValue = UserProp.GetValue(Me, Nothing)
   Return myValue
End Function

Basically a similar method here, again using the PropertyInfo class and then calling the GetValue method passing our custom object, and returning the value we specified when first instantiating the PropertyInfo class.

About the Author, Patrick Santry

Patrick Santry, has two decades of experience in enabling businesses to take advantage of the digital landscape. A well rounded experience in technology, and business is what sets me apart from the rest of the pack. When it comes to an overall digital strategy my experience is impressive.

BS in Computer Information Systems. Four time recipient of the Microsoft MVP Award, and author of several books and magazine articles on digital technologies.

blog comments powered by Disqus


Thank you for visiting our site, before you leave, please visit some of the areas or information you may have missed.

Popular Articles