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
- Adding a reference to the component DLL in Visual Studio
- Adding a
#usingdeclaration to the top of the C# file
- 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.
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
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.
- Part 1: Introduction to C# Reflection
- Part 2: string s = obj.Method()
- Part 3: string s = obj.Method(strString, iNumber)
- Part 4: Setting Object Properties
- Part 5: bool b = obj.Method(iNumber, ref string strString)
- Part 6: bool b = obj.Method(iNumber, out string strString)
- Part 7: Dealing with Remote Objects