Yesterday, I was trying to use reflection to access some properties of a COM object but was getting the following exception:
Object reference not set to an instance of an object
Debugging into, I noticed that GetProperty() method was returning null in the following call:
var propertyInfo = comObject.GetType().GetProperty("PropertyName")
After some searching, I found that we need to use the more generic InvokeMember() method to get or set the properties of a COM object. Here’s the simplest example of the usage:
//get the value of comObject.PropertyName
object propertyValue = comObject.GetType().InvokeMember("PropertyName", System.Reflection.BindingFlags.GetProperty, null, comObject, null);
//set the value of comObject.PropertyName
comObject.GetType().InvokeMember("PropertyName", System.Reflection.BindingFlags.SetProperty, null, comObject, new object[] { propertyValue });
I hope this post helps someone who is trapped into the same situation.
