I have a class that the user can pass an Action into (or not).
public class FooClass<T> : BaseClass<T>
{
public FooClass()
: this((o) => ()) //This doesn't work...
{
}
public FooClass(Action<T> myAction)
: base(myAction)
{
}
}
Basically, I can’t pass null into my base class for the Action. But, at the same time I don’t want to force my user to pass in an Action. Instead, I want to be able to create a “do-nothing” action on the fly.
You want to say
Think of it like this. You need
t => anonymous-expression-body. In this case,anonymous-expression-bodyis anexpressionor ablock. You can’t have an empty expression so you can’t indicate an empty method body with anexpression. Therefore, you have to use ablockin which case you can say{ }to indicate the ablockhas an emptystatement-listand is therefore the empty body.For details, see the grammar specification, appendix B.
And here’s another way to think of it, which is a way that you could use to discover this for yourself. An
Action<T>is a method that takes in aTand returnsvoid. You can define anAction<T>via an non-anonymous method or via an anonymous method. You are trying to figure out how to do it using an anonymous method (or rather, a very special anonymous method, namely a lambda expression). If you wanted to do this via a non-anonymous method you would sayand then you could say
which uses the concept of a method group. But now you want to translate this to a lambda expression. So, let’s just take that method body and make it a lambda expression. Therefore, we throw away the
private void MyAction<T>(T t)and replace it witht =>and copy verbatim the method body{ }.Boom.