tsunami

log in
history

C#: Object Walker

Luke Breuer
2008-03-17 20:14 UTC

Output
------------------------------
The cool way:
------------------------------
Int32 :: MyInteger == 1
String :: MyString == <NULL>

------------------------------
The uncool way:
------------------------------
MyInteger = 1
MyString = <NULL>
Code
using System;
using System.Collections.Generic;

class Program
{
    static void Main(string[] args)
    {
        Foo f = new Foo() { MyInteger = 1, MyString = null };

        Action<string> header = s => Console.WriteLine("{0}\n{1}\n{0}", new string('-', 30), s);

        header("The cool way:");
        Console.WriteLine(ObjectWalker.Walk(f));
    
        header("The uncool way:");
        Console.WriteLine("MyInteger = " + f.MyInteger);
        Console.WriteLine("MyString = " + (f.MyString != null ? f.MyString : "<NULL>"));
    }
}

class Foo
{
    public int MyInteger;
    public string MyString;
}

static class ObjectWalker
{
    public static string Walk(object o)
    {
        System.Text.StringBuilder sb = new System.Text.StringBuilder();
        Type t = o.GetType();

        foreach (System.Reflection.PropertyInfo pi in t.GetProperties())
        {
            object oVal;
            string sVal;

            try
            {
                oVal = pi.GetValue(o, null);

                sVal = oVal == null ? "<NULL>" : oVal.ToString();
            }
            catch (Exception ex)
            {
                sVal = "exception of type " + ex.GetType().Name + " thrown";
            }

            sb.AppendFormat("{0} :: {1} == {2}\n", pi.PropertyType.Name, pi.Name, sVal);
        }

        foreach (System.Reflection.FieldInfo fi in t.GetFields())
        {
            object oVal;
            string sVal;

            try
            {
                oVal = fi.GetValue(o);

                sVal = oVal == null ? "<NULL>" : oVal.ToString();
            }
            catch (Exception ex)
            {
                sVal = "exception of type " + ex.GetType().Name + " thrown";
            }

            sb.AppendFormat("{0} :: {1} == {2}\n", fi.FieldType.Name, fi.Name, sVal);
        }


        return sb.ToString();
    }
}