Table of Content

technology02.pngReflection is a hugely useful technology: it allows you to get inside objects and get their intimate details, modify their values and even rewrite part of their code.
Today I wanted to build a simple treeview control that would display the hierarchical structure of an arbitrary object by going through its properties and building a tree-like structure. Useful to visualise the internals of an object and see changes at runtime.

Using PropertyInfo you get enough information about a particular property to decide if you want to display it or recurse into it if it’s a complex type that contain other properties.

The only big issue I faced was when dealing with indexers.

###The issue with Indexers###

Indexers are defined in code like that:
~~~~brush:csharp
using System;
using System.Collections;

public class DayPlanner
{
// We store our indexer values in here
Hashtable _meetings = new System.Collections.Hashtable();

// First indexer
public string this[DateTime date] {
get {
return _meetings[date] as string;
}
set {
_meetings[date] = value;
}
}

// Second indexer, overloads the first
public string this[string datestr] {
get {
return this[DateTime.Parse(datestr)] as string;
}
set {
this[DateTime.Parse(datestr)] = value;
}
}
}
~~~~
We’ve defined an overloaded indexer: one takes a `DateTime`, the other just a string representation of a date.

We could use them like that for instance:

~~~~brush:csharp
DayPlanner myDay = new DayPlanner();
myDay[DateTime.Parse(“2006/02/03”)] = “Lunch”;

string whatNow = myDay[“2006/06/26”];

Now, say we want to print all property names and their values for an arbitrary object
Let’s try on our `myDay` intance: