6

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.

1 Answer 1

8

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
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the great example. Apparently Reflection is really expensive. Is this true? If so (and there is no other method of doing this), I might write custom web services for each form. Thanks!
Reflection can be expensive when abused. I don't know enough about your projects to say whether or not the overhead of Reflection is acceptable, but there are steps you can take (like caching the PropertyInfo objects you look up in a Dictionary(Of String, PropertyInfo) for faster retrieval) that can reduce that overhead. I'd say, try it and see if it's fast enough. If you find the speed to be unacceptable, then go the route of optimization/caching or your custom web services.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.