The Daily Parker

Politics, Weather, Photography, and the Dog

R is for Reflection

Blogging A to ZOK, I lied. I managed to find 15 minutes to bring you day 18 of the Blogging A-to-Z challenge, in which I'll discuss one of the coolest feature of the .NET ecosystem: reflection.

Reflection gives .NET code the ability to inspect and use any other .NET code, full stop. If you think about it, the runtime has to have this ability just to function. But any code can use tools in the System.Reflection namespace. This lets you do some pretty cool stuff.

Here's a (necessarily brief) example, from the Inner Drive Extensible Architecture. This method, in the TypeInfo class, uses reflection to describe all the methods in a Type:

using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Text;

public static IDictionary<string, MethodInfo> ReflectMethods(object target)
{
	if (null == target) return new Dictionary<string, MethodInfo>();

	var thisType = target.GetType();
	var methods = thisType.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static);

	var returnList = new Dictionary<string, MethodInfo>();
	foreach (var thisMethod in methods.OrderBy(m => m.Name))
	{
		var parameters = thisMethod.GetParameters();
		var keyBuilder = new StringBuilder(thisMethod.Name.Length + (parameters.Length * 16));
		keyBuilder.Append(thisMethod.Name);
		foreach (var t in parameters)
		{
			keyBuilder.Append(";P=");
			keyBuilder.Append(t.ParameterType.ToString());
		}
		keyBuilder.Append(";R=");
		keyBuilder.Append(thisMethod.ReturnType.ToString());
		keyBuilder.Append(";F=");
		keyBuilder.Append(thisMethod.Attributes.ToString());

		try 
		{
			returnList.Add(keyBuilder.ToString(), thisMethod);
		}
		catch (ArgumentException aex) 
		{
			Trace.WriteLine(string.Format(CultureInfo.InvariantCulture, "> Exception on {0}: {1}", keyBuilder, aex.Message));
		}
		catch (Exception ex)
		{
			Trace.WriteLine(string.Format(CultureInfo.InvariantCulture, "> Exception on {0}: {1}", keyBuilder, ex.Message));
			throw;
		}
	}

	return returnList;
}

The System.Reflection.Assembly class also allows you to create and activate instances of any type, use its methods, read its properties, and send it events.

Reflection is hugely powerful and hugely useful. And very, very cool.

Comments are closed