Question Use Variable to Access Different Properties

Doug

Active member
Joined
Oct 5, 2011
Messages
44
Programming Experience
Beginner
I am building a simple search application. It will go through files based on conditions that the user selects such as "Last Modified Date > 1/1/2013" etc. I want to allow users to use any of the fileinfo properties on either side of the condition. With 15 properties that can be on either side of the condition it would be a mess to have to hard code every possible combination.

So I need to be able to use a variable to access the properties rather than hard code the names. How can I do it?
 
Search for: vb.net reflection properties
 
Firstly, why would you want to allow the properties on both sides of the operator? I can't imagine that you'll be comparing the value of one property to another so there'll only ever be one property per condition, so why allow "Last Modified Date > 1/1/2013" and "1/1/2013 < Last Modified Date" when they mean exactly the same thing and allowing only one makes your life easier?

Secondly, I would do as JohnH suggested and use Reflection, which in this case means using the PropertyInfo class, rather than CallByName. Here's a simple example:
Private Function GetMatchingFiles(files As IEnumerable(Of FileInfo),
                                  propertyName As String,
                                  value As Object) As IEnumerable(Of FileInfo)
    Dim prop = GetType(FileInfo).GetProperty(propertyName)

    Return files.Where(Function(fi) prop.GetValue(fi, Nothing).Equals(value))
End Function
 
Back
Top