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.
Expanding the Steven answer a little bit - I needed similar functionality to create an empty delegate for both - Action and Func types - following is the helper that I created for that task:
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.
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:
When you have
EventInfo
you can create an empty lambda for it as follows: