2

Say I have a generic class

class Foo<T>
{
   T fooVal;
   public T FooVal { get { return fooVal; } }
}

and I want to get the FieldInfo for fooVal from an instantiated type:

Foo<int> fooInt = new foo<int>();
FieldInfo fooValField = fooInt.GetType().GetField("fooVal");

The problem is, fooValField is then null. Even if I call GetFields() it returns an empty array. I know the Type is correct because reflection tells me it is Foo'1. I just can't figure out why it doesn't see the fooVal field. Is there something I'm missing here? I can see the FooVal property if I call GetProperties, so I would expect the fooVal field to also show up?

HypnoToad
  • 585
  • 1
  • 6
  • 18
  • 4
    You should use `BindingFlags.NonPublic|BindingFlags.Instance` and overload which allows you to specify them. – user4003407 Apr 04 '16 at 21:38
  • Thanks! I had initially used those BindingFlags, I must have had some other mistake at that time. I thought calling GetFields() without parameters would return *all* fields and would reveal my mistake, but it didn't. I tried again with those BindingFlags and it worked. If you put this as an answer I can give it a big green check mark :) – HypnoToad Apr 04 '16 at 21:46
  • @DavidL I agree it's almost a duplicate although I'm not concerned with attributes. I did try searching first and for some reason that question never came up! – HypnoToad Apr 04 '16 at 21:47
  • There's a typo in there too. You're looking for fooVal, when it's actually FooVal. And if you want to access the value, use InvokeMember. For the instance member, then you'll have to change it to Private Access. – ManoDestra Apr 04 '16 at 21:47
  • @ManoDestra it's not a Typo - I'm looking for the fooVal field, not the FooVal property. I would have left the property out but wanted to show that I was able to get the property but not the field. – HypnoToad Apr 04 '16 at 21:50
  • Well, as I said, you'll need to use private access modifiers in that instance to get to it :) – ManoDestra Apr 04 '16 at 21:52

1 Answers1

2

You need to use

        Foo<int> fooInt = new Foo<int>();
        FieldInfo fooValField = fooInt.GetType().GetField("fooVal", BindingFlags.NonPublic | BindingFlags.Instance);

because the field is not public.

timcbaoth
  • 669
  • 1
  • 7
  • 12