Getting All Static Fields In a Class Hierarchy

Using reflection is pretty straight forward and that's why I found it weird that I was trying to get all the Dependency Properties for the Silverlight ComboBox but I was only getting the fields defined in the class itself. None of the fields found in the base classes where being retrieved. Only then I learned something new about reflection and static fields. Here is the code I expected to work but doesn't.
FieldInfo[] fields =
     typeof (ComboBox).GetFields(BindingFlags.Static | BindingFlags.Public);
When reflecting over a class to get all it's static fields you will find out that static fields from base classes are really not retrieved by default. And since all Dependency Properties are static fields you can't get the DP's from the base classes. If you want to retrieve all the static fields in a class hierarchy you need a special BindingFlag: BindingFlags.FlattenHierarchy. This will bring all your static fields including the one from the base classes.
 FieldInfo[] fields =
     typeof (ComboBox).GetFields(BindingFlags.Static | BindingFlags.Public |
                                 BindingFlags.FlattenHierarchy);

 Hope this is a useful tip.

Find out the calling method

This is one that I found really interesting. I needed to log which methods were calling a certain method, I knew that reflection was the answer but I never thought it would be so easy.

Have you used the CallStack window on your VisualStudio when you are debugging? Well, all that information is available through the System.Diagnostics.StatckTrace class. This means that you have access to method calling stack to do whatever you like.

The StackTrace is composed of an array of StackFrames which represent each method on the stack.

To demonstrate this I’ll create a class with four methods (Method1, Method2, Method3, Method4) which will be called in the following order:

Main -> Method1 -> Method2 -> Method3 -> Method4

class Program
{
    static void Main(string[] args)
    {
        StackTraceTest stt = new StackTraceTest();
        stt.Method1();
    }
}

class StackTraceTest
{
    public void Method1()
    {
        Console.Out.WriteLine("Inside Method1");
        Method2();    
    }

    private void Method2()
    {
        Console.Out.WriteLine("Inside Method2");
        Method3();
    }

    private void Method3()
    {
        Console.Out.WriteLine("Inside Method3");
        Method4();
    }

    private void Method4()
    {
        Console.Out.WriteLine("Inside Method4");
        StackTrace st = new StackTrace();
        StackFrame[] frames = st.GetFrames();
        for (int i = 0; i < frames.Count(); i++)
        {
            Console.Out.WriteLine("StackTrace info: Index: {0}/Method: {1}", 
                i, frames[i].GetMethod().Name);
        }
    }
}

Each method displays a message on the console letting you know that it has been invoked. When the program gets to Method4 it will print the name of the methods on the stack.

Here is the output:

Put a break point on the end of the Method4 and you can take a look at VisualStudios CallStack window to compare with the console output.

As a test you might want to move the StackTrace code to the other methods to see that it will show all the method that led to method currently executing.

For more information look at the StackFrame and MethodBase classes at MSDN.

Reflection on Anonymous Types

Using reflection on anonymous types is just like reflection on any other type.

Consider this simple anonymous object being instantiated:

var anonyObject = new
{
    Name = "Gabriel",
    Age = 31
};

If you want to know all the properties, it’s values and types you can query the object with the reflection classes like this:

//get the type of the anonymous object
Type anonyType = anonyObject.GetType();
//get all the properties info
PropertyInfo[] props = anonyType.GetProperties();
//display each of the properties info
foreach (var prop in props)
{
    Console.WriteLine("Name:{0}, Value:{1}, Type:{2}",prop.Name, 
        prop.GetValue(anonyObject, null), prop.PropertyType);
}

I just wanted to share this code because I’m going to use it in my next article in which I will talk about creating a helper method to transform the result from a Linq query that returns anonymous types to a DataTable.