1

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?

2
  • 1
    Since you already have ExternalSourceProvider in your code at compile time, you don't need reflection to get to ExternalSourceProvider.App ; you'd only need reflection if you were accessing a static member of a type not known at compile time. Commented Nov 14, 2016 at 13:13
  • Also, recall that the . operator has higher precedence than the cast operator. So, I suspect the cast isn't doing what you want.
    – Erik Eidt
    Commented Nov 14, 2016 at 15:27

1 Answer 1

2

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.

2
  • Thanks Telastyn. This question softwareengineering.stackexchange.com/questions/335992/… more clearly indicates what I'm attempting to do. I'm trying to call into the member rather than set it, and PropertyInfo.SetValue wouldn't help. I've upvoted as you give some useful pointers. It'd be great if you're keen to look at the other question ;) Commented Nov 14, 2016 at 2:03
  • @ChrisHalcrow - if it's a method you want to call, then MethodInfo.Invoke. In the end, reflection can do it all (slowly), you just take different routes.
    – Telastyn
    Commented Nov 14, 2016 at 2:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.