(home | about | stats)

pwyky: Introspection

.NET has some nice classes that are similar to the Java reflection implementation. You can do something like this:

class TestRequest
    {
        public string foo = "bar";
        public string bar = null;
        private string fubar = null;
    }

    class Program
    {
        static void Main(string[] args)
        {
            TestRequest t = new TestRequest();

            Type reqType = t.GetType();
            MemberInfo[] members = reqType.GetMembers();

            foreach(MemberInfo member in members)
            {
                if (member.MemberType == MemberTypes.Field)
                {
                    string name = member.Name;
                    FieldInfo info = reqType.GetField(name);
                    object o = info.GetValue(t);
                    if (o != null)
                        Console.WriteLine(name + " " + o);
                }
            }            
        }
    }

to print all the non-null public fields in a class. Now, why would you want to do that? Well, one thing you can do is create a hashtable of key/value pairs:

            Type reqType = t.GetType();
            MemberInfo[] members = reqType.GetMembers();
            Dictionary<string, string> parameters = new Dictionary<string, string>;

            foreach(MemberInfo member in members)
            {
                if (member.MemberType == MemberTypes.Field)
                {
                    string name = member.Name;
                    FieldInfo info = reqType.GetField(name);
                    object o = info.GetValue(t);
                    if (o != null)
                        parameters.Add(name, o.ToString());
                }
            }
www.mobilitytech.com owner. This is a pwyky site.