Cool Programming Functionality: Reflection

In Microsoft's .NET Framewowk, Reflection describes the ability to interpret types dynamically at runtime, or, as the documentation puts it: "The classes in the Reflection namespace, together with System.Type, allow you to obtain information about loaded assemblies and the types defined within them, such as classes, interfaces, and value types. You can also use reflection to create type instances at run time, and to invoke and access them." I've been making use of this lately, and wondering how I could have solved certain tasks without it.

Here's a quick example function in C# that takes a namespace name, class name, and method name as parameters, then instantiates the specified class and calls the specified method. This is just a quickie, so I'm forgoing a lot of things like error handling, etc. The code itself is mine, but the architecture behind it is from a colleague of mine named Bill Butler (Xcent).

public void ExecObjectMethod( string NamespaceName, string ClassName, string MethodName ) {
Assembly targetassembly = null;
Type targettype;
object targetobject = null;

//Load assembly. To load an assembly not directly referenced by the app, you
//could use the LoadFromFile() method.
targetassembly = Assembly.Load( NamespaceName );

//Get the type to instantiate based on ClassName parameter
targettype = targetassembly.GetType( NamespaceName + "." + ClassName );
if( targettype == null ) throw new Exception( "Could not get type " + NamespaceName + "." + ClassName );

//Create an instance of the class
targetobject = Activator.CreateInstance( targettype );

//Call the specified method
//If you wanted, you could also supply parameters to the method
targettype.InvokeMember( MethodName, BindingFlags.InvokeMethod, null, targetobject, null );

//Clean up
targetobject = null;
targetassembly = null;
}

Comments

Popular posts from this blog

A Generic Method Using HttpClient to Make a Synchronous Get Request

The Cause and Solution for the "System.Runtime.Serialization.InvalidDataContractException: Type 'System.Threading.Tasks.Task`1[YourTypeHere]' cannot be serialized." Exception

"$.ajax is not a function" Error When Using jQuery and Darren Johnstone's ASP.NET Upload/Download Module v2