Using LINQ with Reflection in C#

Reflection is used to read meta data from a .Net assembly. For example, if you what to find all the method inside of a .dll, you can use Reflection to do it. You can also load and execute the method. I find it an interesting concept that we have the capability to search and use a method at runtime. To me it opens a door into infinate unknown teritory. It would be possible to write a program without even knowing what it will do, I.e. just write it, run it and see what it does. I digress.

Reflection exposes an IEnumerable interface, therefore it is querible from LINQ. You can check out an article I wrote about Generics in the fundamental section in this website.

So lets write a small method that loads a .Net assembly and finds all the methods within it. I have recently been checking out ODP.NET so lets use the Oracle.DataAccess.dll assembly and see what methods it exposes for us to use.

Be sure to put the Oracle.DataAccess.dll in the working directory of your project, otherwise the program you write can not find it. Or simply add a reference to it.

using System;
using System.Linq;
 
using System.Reflection;
 
namespace LinqToReflection
{
    class Program
    {
        static void Main(string[] args)
        {
            Assembly asmembly = 
                Assembly.Load("Oracle.DataAccess");
 
            var ODPTypes = 
                from type in asmembly.GetTypes()
                    where type.IsPublic
                    from method in type.GetMethods()
                    where 
                        method.ReturnType.FullName 
                            != "System.String"
                    group method.ToString() 
                        by type.ToString();
 
            foreach (var ODPMethods in ODPTypes)
            {
                Console.WriteLine("Type: {0}", 
                    ODPMethods.Key);
                foreach (var method in ODPMethods)
                {
                    Console.WriteLine("    {0}", method);
                }
            }
            Console.ReadLine();
        }
    }
}

We load the assembly using the Assembly.Load method passing it the .dll’s string name. We then loop through all the assembly Types. Types will provide you with the names of the classes that exist within the assembly. Once we get the name of all the class types, we query through classes to get all the methods they expose. If we wanted to, we could then find the parameters for each function and then dynamically use the method.




Download the source.

Leave a Comment

Your email address will not be published.