C# – how to qualify a static member in object derived through reflection

cobject-oriented

I'm trying to reference a member of an object of type 'ExternalSourceProvider' that's been instantiated through reflection like this:

        Type type = GetProviderType(vendor);
        ConstructorInfo constructorInfo = type.GetConstructor(new Type[] { typeof(NameValueCollection) });
        ExternalSourceProvider vendorSourceProvider = (ExternalSourceProvider)constructorInfo.Invoke(new Object[] { requestData });

I now want to set the value for a static member of the newly instantiated object something like this:

        (ExternalSourceProvider)vendorSourceProvider.App = this.App;

I get the error:

Member ExternalSourceProvider.App cannot be accessed with an instance reference, qualify it with a type name instead.

Which is because C# doesn't allow calling static methods with an instance reference

I'm trying to create a pattern where I call an "ExternalSourceProvider.App" member across all children that inherit the base class of type ExternalSourceProvider, so that "ExternalSourceProvider.App" is guaranteed identical across all inheriting children.

How can I achieve what I'm trying to do?

Best Answer

You need to specify the actual type you want the static member of.

Using reflection, you'll need to lookup the static property/field via reflection and call it that way. See PropertyInfo.SetValue (or FieldInfo if it's an actual field).

All that said - static data is distasteful, and if you have to jump through piles of reflection hoops, you're probably doing something evil. Please reconsider.

Related Topic