How to create an empty delegate using Expression Trees?

c# delegates events expression-trees

Question

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.

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 )
{
    Contract.Requires(
        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
    .GetParameters()
    .Select( p => Expression.Parameter( p.ParameterType ) )
    .ToArray();
Delegate emptyDelegate = Expression.Lambda(
    _event.EventHandlerType,
    Expression.Empty(), "EmptyDelegate", true, parameters ).Compile();

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.



Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why