Wednesday, December 29, 2010

How to tell if a property exists by name

I recently was working on a library to manage reports in an application (probably a good candidate for an open source project) and needed to be able to grab the value of a property on an object by name without knowing if that property existed or not.  Of course .NET reflection comes in handy for doing this, and this is the easy wrapper code I came up with.  Just add this to any class to query for the existence of a property or to retrieve its value as a string.  There's way more you can do with reflection, but this wraps up at least some of the basics.


''' <summary>
''' Indicates if a property exists on this object by name
''' </summary>
''' <param name="PropertyName">The CASE SENSITIVE name of the property on this object</param>

Public Function PropertyExistsByName(ByVal PropertyName As String) As Boolean
    Try
        Return Me.GetType().GetProperty(PropertyName) IsNot Nothing
    Catch ex As Exception
        Return False
    End Try
End Function



''' <summary>
''' Returns the value of a public property on this object by name
''' </summary>
''' <param name="PropertyName">The CASE SENSITIVE name of the property on this object</param>
''' <param name="ReturnIfNotFound">What to return if the property is found not to exist or if there is an error.</param>

Public Function GetPropertyValueByName(ByVal PropertyName As String, Optional ByVal ReturnIfNotFound As String = "") As String
    Try
        If PropertyExistsByName(PropertyName) Then
            Return Me.GetType().GetProperty(PropertyName).GetValue(Me, Nothing).ToString
        Else
            Return ReturnIfNotFound
        End If
    Catch ex As Exception
        Return ReturnIfNotFound
    End Try
End Function

1 comment: