How can I use Expression Trees to construct an empty delegate?

c# delegates events expression-trees


Using anonymous methods you can create empty delegates since C# 2.0.

public event EventHandler SomeEvent = delegate {};
public event Action OtherEvent = delegate {};

This is e.g. useful to prevent having to do the null check when invoking events.

How can I create the same behavior using Expression Trees?

The only possible option I see now is to use Expression.Lambda(), but as far as I can tell this would require a lot of extra work.

5/23/2017 12:17:20 PM

Accepted Answer

As it turns out it isn't that much work using Expression.Lambda(). However, I'm still interested in possible other answers.

I did need a helper method which I wrote previously:

/// <summary>
///   The name of the Invoke method of a Delegate.
/// </summary>
const string InvokeMethod = "Invoke";

/// <summary>
///   Get method info for a specified delegate type.
/// </summary>
/// <param name = "delegateType">The delegate type to get info for.</param>
/// <returns>The method info for the given delegate type.</returns>
public static MethodInfo MethodInfoFromDelegateType( Type delegateType )
        delegateType.IsSubclassOf( typeof( MulticastDelegate ) ),
        "Given type should be a delegate." );

    return delegateType.GetMethod( InvokeMethod );

When you have EventInfo you can create an empty lambda for it as follows:

EventInfo _event;


MethodInfo delegateInfo
    = DelegateHelper.MethodInfoFromDelegateType( _event.EventHandlerType );
ParameterExpression[] parameters = delegateInfo
    .Select( p => Expression.Parameter( p.ParameterType ) )
Delegate emptyDelegate = Expression.Lambda(
    Expression.Empty(), "EmptyDelegate", true, parameters ).Compile();
3/22/2012 1:54:45 PM

Popular Answer

An expression tree, by nature of its purpose, always has an expression for a body rather than a statement in the original design.

In C# 3 there was no way at all to express an expression tree whose body is an empty statement block. More recently, the expression tree library has been extended to allow for statements, but the C# semantic analysis rules were not updated to take advantage of that; you still cannot turn a statement lambda into an expression tree.

Related Questions

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow