I’m setting up a simple helper class to hold some data from a file I’m parsing. The names of the properties match the names of values that I expect to find in the file. I’d like to add a method called AddPropertyValue to my class so that I can assign a value to a property without explicitly calling it by name.
The method would look like this:
//C#
public void AddPropertyValue(string propertyName, string propertyValue) {
//code to assign the property value based on propertyName
}
---
'VB.NET'
Public Sub AddPropertyValue(ByVal propertyName As String, _
ByVal propertyValue As String)
'code to assign the property value based on propertyName '
End Sub
The implementation might look like this:
C#/VB.NET
MyHelperClass.AddPropertyValue("LocationID","5")
Is this possible without having to test for each individual property name against the supplied propertyName?
You can do this with reflection, by calling
Type.GetPropertyand thenPropertyInfo.SetValue. You’ll need to do appropriate error handling to check for the property not actually being present though.Here’s a sample:
If you need to do this a lot, it can become quite a pain in terms of performance. There are tricks around delegates which can make it a lot faster, but it’s worth getting it working first.