Roy Osherove

View Original

Method_Missing: Cool Uses

I wrote the other day that I’ve added that ability to use a Method_Missing method in VB. I was also able to get something similar in C# 4 using dynamic types but people keep asking me “why is it useful?”

I thought long and hard and the first answer I came up with was “cause it sounds like a cool idea”.

Then I started looking up potential uses for this.This feature is used all over the place in ruby on rails and such, to have "smart" methods that know what you need without you needing to define it beforehand.
good examples here:
http://szeryf.wordpress.com/2008/06/05/eliminating-code-duplication-with-metaprogramming/
http://szeryf.wordpress.com/2007/07/15/extending-rails-magic-%EF%AC%81nders/
http://redhanded.hobix.com/inspect/theBestOfMethod_missing.html

 

Today at work I thought of another cool use for such a thing: a proxy to private method invocations

When working with a type who has non public methods that you with to invoke, you can easily create a “wrapper” class that you can call those methods directly on, which, when Method_Missing gets called, will be redirected as reflection invocation calls against that object.

 

Assuming you has method_missing support in VB and in C# out of the box – what would you use it for?