Friday, March 23, 2012

C# : Logging the variables in a class


Imagine you have a web site with a bunch of global variables. You want to display them in a debug page. So you could use intellisense and manually traverse through the class but if it’s a big class it’s a right royal pain and you have to keep updating the code as you add new variables.

Enter stage right Reflection.

Type objectType = typeof (GlobalVar);
GlobalVar gv = new GlobalVar();
System.Reflection.FieldInfo[] fieldInfo = objectType.GetFields();

foreach (System.Reflection.FieldInfo info in fieldInfo)
xxx.Text = info.Name;

object oText = info.GetValue(null);
if (oText is string)
yyy.Text = (String)oText;
else if (oText is int)
yyy.Text = oText.ToString();
else if (oText is bool)
yyy.Text = oText.ToString();
else if (oText is long)
yyy.Text = oText.ToString();

Note the “GetValue(null); “. This is because all the variables in the class are static.

For a non-static class, see C# Tutorial - Using Reflection to Get Object Information.


No comments: