Chris McCall
Chris McCall

Reputation: 10397

What's wrong with this reflection code? GetFields() is returning an empty array

C#, Net 2.0

Here's the code (I took out all my domain-specific stuff, and it still returns an empty array):

using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            ChildClass cc = new ChildClass();
            cc.OtherProperty = 1;

            FieldInfo[] fi = cc.GetType().GetFields();
            Console.WriteLine(fi.Length);
            Console.ReadLine();
        }
    }
    class BaseClass<T>
    {
        private int myVar;

        public int MyProperty
        {
            get { return myVar; }
            set { myVar = value; }
        }


    }

    class ChildClass : BaseClass<ChildClass>
    {
        private int myVar;

        public int OtherProperty
        {
            get { return myVar; }
            set { myVar = value; }
        }

    }
}

Upvotes: 31

Views: 31650

Answers (3)

AgileJon
AgileJon

Reputation: 53586

You need to specify that you want the private (NonPublic) fields

Change to:

FieldInfo[] fi = cc.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Instance);

Upvotes: 5

Jon Skeet
Jon Skeet

Reputation: 1499860

The parameterless GetFields() returns public fields. If you want non-public ones, use:

cc.GetType().GetFields(BindingFlags.Instance | BindingFlags.NonPublic);

or whatever appropriate combination you want - but you do need to specify at least one of Instance and Static, otherwise it won't find either. You can specify both, and indeed public fields as well, to get everything:

cc.GetType().GetFields(BindingFlags.Instance | 
                       BindingFlags.Static |
                       BindingFlags.NonPublic |
                       BindingFlags.Public);

Upvotes: 79

Reed Copsey
Reed Copsey

Reputation: 564363

Since the field is private, you need to use the overload of GetFields() that allows you to specify BindingFlags.NonPublic.

To make this work, change it to:

FieldInfo[] fi = cc.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Instance);

Upvotes: 12

Related Questions