/* * Accessing another's class private fields * Written by: Eber Irigoyen * http://ebersys.blogspot.com * on: 12/17/2006 * License: LGPL * Description: * Demonstrates code to get a list of another's class private members */ using System; using System.Collections.Generic; using System.Text; using System.Reflection; namespace ClassPrivateFields { class TestClass { private int prop1; public int Prop1 { get { return prop1; } set { prop1 = value; } } private string prop2; public string Prop2 { get { return prop2; } set { prop2 = value; } } private bool prop3; public bool Prop3 { get { return prop3; } set { prop3 = value; } } public bool field4; public TestClass() { prop1 = 10; prop2 = "20"; prop3 = false; field4 = true; } } class Program { static void PrintPrivateFields(T theInstance) where T:class { Type t = theInstance.GetType(); FieldInfo[] fields = t.GetFields(BindingFlags.NonPublic | BindingFlags.Instance); foreach (FieldInfo f in fields) Console.WriteLine(string.Format("type:{0} \t value:{1}", f.FieldType.ToString(), f.GetValue(theInstance))); } static void Main(string[] args) { TestClass test = new TestClass(); FieldInfo[] fields = test.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Instance); foreach (FieldInfo f in fields) Console.WriteLine(string.Format("type:{0} \t value:{1}", f.FieldType.ToString(), f.GetValue(test))); PrintPrivateFields(test); Console.ReadLine(); } } }