Greg Young [MVP]

Sponsors

The Lounge

Wicked Cool Jobs

News

Advertisement

Delegate Mapper

When I was in Holland Jelle Hissink pointed out a quick easy piece of code that is extremely useful in many scenarios I have seen in the past. It maps delegates from Base classes to Derived classes. Previously working with messaging I used the Handles<T> methodology which has since become popular in both MassTransit and nServiceBus. It allowed you to use typed message handlers as opposed to having to write handlers that used the base class then casted to the specific type. This code does the same but using delegates which is pretty slick and can be used in an aggregate root base class quite easily to handle the mapping of events to methods that apply them internally (you can also use it for event/command handlers if you don’t want to use an existing framework such as nServiceBus or MassTransit). Here is the code.

public class DelegateAdjuster
{
    public static Action<BaseT> CastArgument<BaseT, DerivedT>(Expression<Action<DerivedT>> source) where DerivedT : BaseT
    {
        if (typeof(DerivedT) == typeof(BaseT))
        {
            return (Action<BaseT>)((Delegate)source.Compile());

        }
        ParameterExpression sourceParameter = Expression.Parameter(typeof(BaseT), "source");
        var result = Expression.Lambda<Action<BaseT>>(
            Expression.Invoke(
                source,
                Expression.Convert(sourceParameter, typeof(DerivedT))),
            sourceParameter);
        return result.Compile();
    }
}

 

Simple, and slick.


Posted Sat, Oct 3 2009 7:27 AM by Greg

[Advertisement]

Comments

Nick Palladinos wrote re: Delegate Mapper
on Sat, Oct 3 2009 8:18 AM

public static Action<BaseT> CastArgument<BaseT, DerivedT>(Action<DerivedT> source)

where DerivedT : BaseT

{

return baseValue => source((DerivedT) baseValue);

}

DotNetShoutout wrote Delegate Mapper - Greg Young - CodeBetter.Com
on Mon, Oct 5 2009 2:38 AM

Thank you for submitting this cool story - Trackback from DotNetShoutout

Sanjeev Agarwal wrote Daily tech links for .net and related technologies - October 5-7, 2009
on Tue, Oct 6 2009 4:26 AM

Daily tech links for .net and related technologies - October 5-7, 2009 Web Development How To Speed Up

PimpThisBlog.com wrote Delegate Mapper
on Sun, Oct 11 2009 9:05 PM

Thank you for submitting this cool story - Trackback from PimpThisBlog.com

Add a Comment

(required)  
(optional)
(required)  
Remember Me?
Devlicio.us