Runtime DLL Linking through Reflection

What is Reflection?

In Computer Science, Reflection generally refers to the ability of a program to examine, inspect, and modify its own structure and behavior during runtime.

The System.Reflection namespace allows us to get information about assemblies, modules, members, methods, parameters, events and other things by examining their metadata. This can be used to create and use instances of types that were loaded at runtime. Through reflection, we can load assemblies or class libraries, instantiate an object from a Type in said assembly, invoke methods and get field values.

Creating the DLL file

Lets imagine that we have a class library (.dll file) called BlogExampleDLL and inside we create a class file called Test.cs.

Now we can build the assembly and we’ll get a BlogExampleDLL.dll file in our output directory.

Using the DLL file from another program

We will now construct a Console Application program that will be used to manipulate the data in the BlogExampleDLL class library, lets call this Console program BlogDLLExampleInformation. This is how an empty console application looks.

First we have to load up the BlogExampleDLL assembly, we will now use the System.Reflection namespace.

Now that your class library is loaded, we need to get can information on the types of entities it contains using the
asm.GetTypes()
method which returns an array of Types. Iterating through the array, we get the output:-

There is only 1 type ‘Test‘ in the assembly, which is our Test class. We can save this class in a Type variable for further inspection.

Type Information

Now that we have stored the type of our class in a variable, we can use reflection to get information about the class i.e. its methods, fields, events etc. It has several methods which help us get information about a class:-

  • GetConstructors()
  • GetCustomAttributes()
  • GetEvents()
  • GetFields()
  • GetMembers()
  • GetMethods()
  • GetProperties()

We can iterate through the array returned by these methods to get information on the class. For example:-

And the output we get is:-

That’s all for today folks, stay tuned for my post on how we can instantiate these classes and invoke their methods and get the value of their fields.

Other Stuff

Social

AryanMann Written by: