Menu
Carl Camera

C# Reflection Part 1

For those who are unfamiliar with .NET reflection, it is a whole area of computing that allows runtime binding to public classes, methods, and properties within external DLLs. Some folks refer to this as late binding.

In .NET, the usual way we call a method in another project's Data Link Libarary (DLL) is by

  1. Adding a reference to the component DLL in Visual Studio
  2. Adding a #using declaration to the top of the C# file
  3. Calling the method just as you would call a local method

In the example above, we performed early binding -- at compile time. Late binding waits until the moment the program (while it's running) is about to call the method before actually binding to the external component and invoking a method within the component. This is accomplished in a somewhat longer manner that I will cover is a series of articles.

Gathering Information

All we have to start with is a DLL that was created by someone. This exercise assumes that we know the following about the DLL

  • the path to the DLL at run time
  • the signature of the method we want to invoke
  • the return type of the method we want to invoke
  • knowledge that the class and its method are declared as public

The path and return type of methods are easily understood. It goes to reason that if the class or method are not declared as public then they cannot be accessed via reflection. You might not be familiar with the term signature.

In C#, a method signature consists of the method name, and the number and types of parameters passed to it. It is perfectly fine to have all of these methods defined within one class:

string[] GetCustomerName(string strSearch)
string[] GetCustomerName(string strSearch, string strState)
string[] GetCustomerName(string strSearch, int iMaxNames)
string GetCustomerName(int iCustNumber)

The C# compiler is able to determine which method you want to call based on the number and types of parameters you send it. We see this in play with IntelliSense that often shows 1 of 6, for instance, when typing in a method name. The return type is not factored into a method's signature, only the number and types of parameters.

So just knowing the name of the method isn't sufficient. To call the correct method, we'll have to find the method by its name and its parameter count and those parameters' types.

Now that we've gathered our information, we'll walk through the examples one by one.

Comments