Practical .NET

Processing All Properties on an Object

If you ever need to work with all of the properties in some object, you can use GetType and GetProperties to retrieve the object's PropertyInfo objects. After that you can do what you want. Here's an extension method that sets all those properties to their defaults, for example.

Every once in a while I want to do something with all the properties on an object. The .NET Framework gives me the GetType method which returns a Type object for an object and the Type object's GetProperties method gives me a PropertyInfo object for each property in the object. Armed with those PropertyInfo objects, I can retrieve/set property values and determine if a property holds a value type (integers, dates, etc.) or a reference type (some object), among other cool tricks.

For example, sometimes I need an object with all of its properties all set to their default values. In the bad old days, I would create a new instance of the object even if I already had a copy of the object lying around. Eventually, I created an extension method (shown in Listing 1) that loops through all the properties on any object, resetting each property to its default value.

Listing 1: Extension Method To Reset Property Values

Module PHVExtensions
    <Extension>
    Public Sub SetPropertiesToDefaultValues(Of T)(obj As T)
        Dim props = obj.GetType.GetProperties()
        Dim propType As Type
        For Each prop In props
            propType = prop.GetType
            If prop.PropertyType.Name = "String" Then
                prop.SetValue(obj, String.Empty)
            ElseIf propType.IsValueType Then
                prop.SetValue(obj, Activator.CreateInstance(propType))
            Else
                prop.SetValue(obj, Nothing)
            End If
        Next
    End Sub
End Module

You'll notice that I have a special test to handle the String type. You might prefer to omit that code, in which case String properties will be set to null/Nothing.

You would use this extension method like this:

Dim cust As Customer
cust = New Customer("A123")
cust.SetPropertiesToDefaultValues()

What will you do with all the time you save?

About the Author

Peter Vogel is a system architect and principal in PH&V Information Services. PH&V provides full-stack consulting from UX design through object modeling to database design. Peter tweets about his VSM columns with the hashtag #vogelarticles. His blog posts on user experience design can be found at http://blog.learningtree.com/tag/ui/.

comments powered by Disqus

Featured

Subscribe on YouTube