Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VB .NET Access a class property by string value

Tags:

vb.net

I have a function that updates a Client in the database. A client object is passed in, along with a string array of fields/properties that should be updated. I need a way of accessing each property in the client object, based on what is in the array. Basically, I am looking for the VB .NET equivalent to this javascript:

var fields = ["Firstname","Lastname","DOB"];
for(field in fields)
{
    var thisField = fields[field];
    client[thisField] = obj[thisField];
}

Any help will be greatly appreciated! Thanks Stack.

like image 252
Brett Avatar asked Nov 16 '10 03:11

Brett


1 Answers

You can use Reflection to do this. Without knowing more about how your data objects are set up, I can't give you a perfect example, but here's the general idea:

Dim myPerson As New Person
myPerson.FirstName = "John"
myPerson.LastName  = "Doe"
myPerson.DOB       = #1/1/2000#

Dim myUpdates As New Dictionary(Of String, Object)
myUpdates.Add("FirstName", "Adam")
myUpdates.Add("LastName" , "Maras")
myUpdates.Add("DOB"      , #1/1/1990#)

Dim personType As Type = GetType(Person)

For Each kvp As KeyValuePair(Of String, Object) In myUpdates
    Dim propInfo As PropertyInfo = personType.GetProperty(kvp.Key)

    If propInfo IsNot Nothing Then
        propInfo.SetValue(myPerson, kvp.Value)
    End If
Next
like image 194
Adam Maras Avatar answered Oct 22 '22 13:10

Adam Maras