Set Properties on Reflected Object
Suppose that the method that we will eventually call requires that two properties within the object be set beforehand. Why would anyone design a class this way? I can't explain it but there is code out in the wild (ahem) that might require this. If you're one of the other unfortunate ones, here's how to set properties on an object created through reflection.
Setting properties through reflection requires both a Type
object and an object
instantiation. We create these as shown in Part 2:
Assembly assem = Assembly.LoadFrom(@"c:\path\to\file.dll");
Type typClsX = assem.GetType("Fully.Qual.ClsX",true);
object oClsX = Activator.CreateInstance(typClsX);
Now with instantiated object in hand, we can create a PropertyInfo object that can interact with the properties within that target object.
System.Reflection.PropertyInfo p_i;
p_i = typClsX.GetProperty("CustomerType");
p_i.SetValue(oClsX,"Commercial",null)
The first line simply defines a PropertyInfo
variable p_i
. The next line
populates the p_i
object with information known about the CustomerType property by the
System.Type object typClsX
. The third line sets the value of the property within the instantiated object (known
to be a string in this example) to a value.
The null
value in the third line indicates that there is no indexer to the property.
If the property were a string array, for instance, the second parameter would indicate
which array element to set.
p_i
can be reused to set the second property:
int iCountryCode = 38;
p_i = typClsX.GetProperty("CustomerCountry");
p_i.SetValue(oClsX,iCountryCode,null)
This time, we're setting an integer property value. If CustomerCountry
were not an integer
property, .NET will throw a TargetException error.
The Snippet
That's the full explanation of setting values on reflected objects. When invoking methods on that object after this point, the object will draw upon the properties as you have set them.
// create target object
Assembly assem = Assembly.LoadFrom(@"c:\path\to\file.dll");
Type typClsX = assem.GetType("Fully.Qual.ClsX",true);
object oClsX = Activator.CreateInstance(typClsX);
// set the CustomerType property
System.Reflection.PropertyInfo p_i;
p_i = typClsX.GetProperty("CustomerType");
p_i.SetValue(oClsX,"Commercial",null)
// set the CustomerCountry property
int iCountryCode = 38;
p_i = typClsX.GetProperty("CustomerCountry");
p_i.SetValue(oClsX,iCountryCode,null)
Summary
In this article we learned how to set properties to an object created via .NET reflection.
- Part 1: Introduction to C# Reflection
- Part 2: string s = obj.Method()
- Part 3: string s = obj.Method(strString, iNumber)
- Part 4: Setting Object Properties
- Part 5: bool b = obj.Method(iNumber, ref string strString)
- Part 6: bool b = obj.Method(iNumber, out string strString)
- Part 7: Dealing with Remote Objects
Comments