Alex Rivera | Logout

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

Asked 2009-06-24T20:30:32.017
32

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; }
        }

    }
}
Edit
Report

1 Answer

5

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

Change to:

FieldInfo[] fi = cc.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Instance);
answered 2009-06-24T20:32:31.323

Your Answer