Link to home
Start Free TrialLog in
Avatar of cmhunty
cmhunty

asked on

Setting a property from a string value

Hi

I have a class names Customer with several properties. I have the property I wish to set in one string and the value to set it to in another.

       Dim cust As New Customer
        Dim strProp As String = "name"
        Dim strVal As String = "Chris"

Is there a simple way of setting the property in strProp the the value in strVal?

I've written a function to do it using TypeDescriptor.GetProperties(obj) to get the properties, then finding the one I want and setting it that way but I can't believe this is the quickest way.

Thanks

Chris
ASKER CERTIFIED SOLUTION
Avatar of Bob Learned
Bob Learned
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Unless you want to rewrite your Class to use a different method of storing your properties, this IS the easiest way to do it, based on the strings.

If you wanted to do it differently, you could consider using a hashtable in your class to store values, and use the property name string as your key for the hashtable.

That way, you could say

Obj.HashTable.Item("Key") = "Value"

Otherwise, you're doing it the right way.

Jake
Oh Bob,

You always have a much better way of doing things...  Didn't know about that one!

Jake

P.S.  Will that cut down on time?  I.e., his algorithm probably loops through all properties till it finds the right one, whereas .net finds the relevant property for you in your example?
Reflection is not the most efficient operation type, but this one should be OK, as it is not too heavy.

Bob
Thanks for the info, Bob.

You constantly amaze me with your knowledge of Reflection :)

Jake
Avatar of cmhunty
cmhunty

ASKER

Cheers guys.

This was related to https://www.experts-exchange.com/questions/22774145/Problem-downgrading-TypeDescriptor-GetProperties-from-NET-2-0-to-1-1.html

Thanks for the help with Reflection and I'll issue points but I still can't get it working for .NET1.1 with custom classes as in the link. All very strange. Works fine with 2.0.