Thursday, December 15, 2011

A Reflective Question

I was recently asked a Question in an interview about Creating a function that can read reflection of certain aspects off a class instance. (some version of debugger … I guess)

anyway, here’s my solution (using recursion of course)

private static string Reflective(string instanceName, Type type, object obj, int depth)
{
StringBuilder sb = new StringBuilder();

string format = "* <{0}> {1}";
for (int i = 0; i <= depth; i++)
format = ("\t") + format;

sb.AppendFormat("\n" + format,
type.Name, instanceName);

if (obj == null)
return sb.ToString()
+ "-> {Null}";

FieldInfo[] fields = type.GetFields();
foreach (FieldInfo fld in fields)
{
format = "<{2}> {0}={1}";
for (int i = 0; i <= depth; i++)
format = ("\t") + format;
if (fld.FieldType.IsPrimitive)
{
string val = (obj==null)? "NULL" : fld.GetValue(obj)+"";
sb.AppendFormat("\n\t" + format,
fld.Name, val, fld.FieldType.Name);
}
else
{
sb.Append(
Reflective(fld.Name, fld.FieldType,
fld.GetValue(obj),
depth+1));
}
}
return sb.ToString();
}
}



How to use



var computer = new Computer
{
CPUs = 4,
Display = null,
AnotherDisp = new Monitor {
Height = 768, Width = 1024, Zoom = 2
}

};


string s = Reflective("computer", computer.GetType(), computer, 0 );
Console.WriteLine(s);



Will print out



* <Computer> computer

        * <Monitor> Display-> {Null}


        <Int32> CPUs=4


        * <Monitor> AnotherDisp


                <Int32> Width=1024


                <Int32> Height=768


                <Int32> Zoom=2