Monday, August 23, 2010

Invoke a lambda function through reflection

Introduction
At work I was writing a small library for a customer - in this library you are able to setup strongly-typed seaching objects that uses lambda expressions to search through a domain model.
All-in-all a nice little library that worked fast and was easy to use. But I came across a problem when I needed to combine two or more search-objects. It is a small article that shows you how you can invoke a generic lambda function through reflection.
Background
If you have the following class defined in your domainmodel:

  1. public
     class LambdaClass<t>  
  2. {  
  3.     public Func<t, bool=""> TestMethod { getset; }  
  4.   
  5.     public LambdaClass(Func<t, bool=""> testMethod)  
  6.     {  
  7.         TestMethod = testMethod;  
  8.     }  
  9. }

You can use this class like this:


  • LambdaClass<string> lambdaTest = new LambdaClass<string>(entry => entry.Contains("Tom"));  



  • if (lambdaTest.TestMethod("My name is Tom"))   



  • {  



  •    Console.WriteLine("Yes it is");   



  • }  


  • This is all fine - but what if I need to call the TestMethod on the LambdaClass but I don't know the generic type?!
    Using the code
    It is possible and to do this, but we have to introduce a new interface for all of this to work properly - we need to make a little abstraction and have the possibility to get the generic type.
    Read more: Codeproject