Thursday, March 11, 2010
 
   
 
Welcome to my site

First let me say thanks for stopping by my site. My name is David Hanson-Graville and I am a IT consultant working in the UK. Let me make it clear, I am passionate about technology and specifically .net and its various forms. I've programmed in a range of langages, but I can say, I am now at my happiest when coding with c#. I hope my blog is an enjoyable & educational read and please feel free to email me at David.Hanson@OnTheBlog.net if you have any questions. 

Calling a generic method with Expression.Call Minimize
Location: BlogsOnTheBlog    
Posted by: David Hanson Sun, 17 Jan 2010 09:05:54 GMT

The other day I came across a comment in the code base of the application I'm currently working on that said the following.

// Having to loop through the GetMethods() array is pretty rubbish, even if we are using LINQ. If someone knows how to use GetMethod to get the generic method definition, then correct the code, email me and I'll buy you a pint.

Now looking into this issue it turns out that the author is correct, you cannot actually use Type.GetMethod() to invoke a Generic Method. As a result the approach the dev used was to call Type.GetMethods() which returns all methods on the type and then apply some linq filtering to identify the generic method they wish to invoke. Once filtered a quick call to MakeGenericMethod then you can invoke it. This is shown below.

typeof(FrameworkHelper)
    .GetMethods()
    .Where(method => method.IsGenericMethod && method.Name == "DeleteEntity")
    .Select(method => method.MakeGenericMethod(actualEntityType))
    .First()
    .Invoke(null, new object[] { entity });

So having a think about this for a bit and then recalling some great blog posts I had read from Bart De Smet's blog about expression tree's I wondered if we could use the Expression.Call method to achieve the same results. After some tinkering with the overloads for this method I eventually figured it out and result is shown below.

ParameterExpression param = Expression.Parameter(typeof(Entity), "param");
var method = Expression.Call(typeof(FrameworkHelper), "DeleteEntity", new[] { typeof(Entity) }, param).Method;
method.Invoke(null, new object[] { entity });

In the code above we create an instance of a Parameter expression which requires the Type of the parameter we are going to pass to the method. Then in order to invoke the method we need to build the call expression on line 2. Here we use the Expression.Call static method which has a number of overloads.

The first param is the type which holds the static method we wish to invoke, the next paramter is the method name which is passed as string. The third paramter is the types that the method signature defines. This is passed as an array of objects. Finally is the ParamExpression we constructed on the previous line. The final part once we have the methodInfo is to invoke it by passing the instance of Entity. 

The Expression class supports a huge array of static methods which can be used to build code dynamically and with .NET 4.0 we get a lot more support for more complex issues such as flow control, block statements etc. 

 Hope this quick sample sparks your interest for Expressions support in .net.

Update - Had an email from Bart about this post and he has suggested an elegant approach to this problem. Bart's approach below.

You could also have the C# compiler do all the work for you and write a simple helper method (assuming you don't need to find the method by an externally provided name at runtime...):

static MethodInfo GetMethod(Expression e)
{
return ((MethodCallExpression)e.Body).Method;
}

Now call this as follows:

GetMethod(() => new int[0].Select(x => x.ToString()))

This will return the MethodInfo for Enumerable.Select.

Hope this helps,
-Bart

Permalink |  Trackback

Your name:
Title:
Comment:
Security Code
Enter the code shown above in the box below
Add Comment   Cancel 
Tweets Minimize
Twitter / LordHanson
  1. LordHanson: My vaio p is doing well while travelling. 3g Internet, HD movies, digital tv, photo editing, wifi router for iPods and much more. Love it

    Published Wed, 10 Mar 2010 10:29:19 +0000 by
  2. LordHanson: Ok so I need to stay techie while away from a computer for a year. Anyone got any ideas.

    Published Mon, 22 Feb 2010 12:31:09 +0000 by
  3. LordHanson: Sitting in YHA Glebe Sydney waiting for the movie night to start

    Published Thu, 18 Feb 2010 08:13:10 +0000 by
  4. LordHanson: Madness today. We only booked our return tickets to bangkok on the wrong day! Luckily we managed to change them!

    Published Wed, 10 Feb 2010 15:54:37 +0000 by
  5. LordHanson: HTML5 the future? http://bit.ly/6yf9Bu

    Published Tue, 09 Feb 2010 13:43:48 +0000 by
  6. LordHanson: Last night in Bangkok! Good fun!

    Published Thu, 04 Feb 2010 18:09:38 +0000 by
  7. LordHanson: @trampussandal Dad? lol

    Published Thu, 04 Feb 2010 05:26:39 +0000 by
  8. LordHanson: Im sitting in a coffee shop in my home town of epsom thinking... Man the day has finally arrived. I can feel the stress lifting.

    Published Mon, 01 Feb 2010 09:05:13 +0000 by
  9. LordHanson: So what excuse will apple use to not allow flash or silverlight to run on the ipad this time I wonder.

    Published Fri, 29 Jan 2010 19:07:46 +0000 by
  10. LordHanson: Yay just manage to upgrade from vista ultimate to windows 7 enterprise by using the registry hack trick. No reinstalls.

    Published Wed, 27 Jan 2010 07:18:07 +0000 by
  11. LordHanson: @swhelband Sure am...http://bit.ly/aZ6Xvd

    Published Tue, 26 Jan 2010 19:05:18 +0000 by
  12. LordHanson: I finished work today in prep for travelling. I must admit as i left the office i felt a little emotional. Sign of a good job with great ...

    Published Tue, 26 Jan 2010 17:48:49 +0000 by
  13. LordHanson: So, today is my last day of work before i leave for australia. And it just happens to fall on australia day too. How very cool.

    Published Tue, 26 Jan 2010 08:51:42 +0000 by
  14. LordHanson: Well woke up at dads this morning. Didn't sleep too bad considering.

    Published Sun, 24 Jan 2010 10:08:25 +0000 by
  15. LordHanson: RT @BillGates: My new website is live check out www.thegatesnotes.com. Excited to share more about what I’m learning, hope you like it!

    Published Fri, 22 Jan 2010 14:11:24 +0000 by
  16. LordHanson: @DJTravelling need to watch out of people carrying illness over the next week. They are everywhere!

    Published Fri, 22 Jan 2010 08:22:24 +0000 by
  17. LordHanson: Lots of sick sounding people creeping onto the trains today. Stay away stay away!

    Published Fri, 22 Jan 2010 08:14:36 +0000 by
  18. LordHanson: @RoyOsherove come back to the conchango offices for some real fusball competition!

    Published Thu, 21 Jan 2010 22:49:34 +0000 by
  19. LordHanson: RT @connectifyme: #Connectify Blog: Announcing Connectify v1.1! http://bit.ly/5og7vI

    Published Wed, 20 Jan 2010 16:31:48 +0000 by
  20. LordHanson: LMAO RT @colmbrophy: so have you seen who owns http://wwwbing.com ? it's not microsoft

    Published Tue, 19 Jan 2010 17:35:43 +0000 by
Print  
Archive Minimize
Print  
Contact me Minimize
Print  
Microsoft Certs Minimize







Print  
Silverlight News Minimize
Silverlight - Google News
  1. MSN Video takes on BBC iPlayer with ad-supported online TV offering - The Guardian

    Published Wed, 10 Mar 2010 17:37:35 GMT+00:00 by
  2. MSN decides to keep its makeover - CNET

    Published Tue, 09 Mar 2010 17:00:15 GMT+00:00 by
  3. Adobe, Microsoft Bringing Flash To Windows Phones - ChannelWeb

    Published Thu, 11 Mar 2010 00:53:11 GMT+00:00 by
  4. Where to Watch March Madness Online - NewTeeVee (blog)

    Published Thu, 11 Mar 2010 02:03:27 GMT+00:00 by
  5. Windows Phone 7 to support .NET, Silverlight, XNA - Seattle Post Intelligencer (blog)

    Published Fri, 05 Mar 2010 02:23:29 GMT+00:00 by
  6. Small Basic 0.8 and Silverlight - Softpedia

    Published Tue, 09 Mar 2010 11:59:10 GMT+00:00 by
  7. Microsoft banks Windows Phone 7 on Silverlight - Register

    Published Thu, 18 Feb 2010 06:02:11 GMT+00:00 by
  8. Adobe, Microsoft Spar Over Flash, Silverlight, HTML5 - InformationWeek

    Published Fri, 05 Mar 2010 21:48:08 GMT+00:00 by
  9. Microsoft VOD service - IAB UK

    Published Wed, 10 Mar 2010 15:08:14 GMT+00:00 by
  10. Android Could Soothe Microsoft's Silverlight Itch - AndroidGuys (blog)

    Published Sat, 06 Mar 2010 14:41:12 GMT+00:00 by
Print