C #: create action Do-nothing Action on class

I have a class that the user can pass Action (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 cannot pass null to my base class for Action . But at the same time, I do not want my user to go to Action . Instead, I want to be able to create an β€œdo nothing” action on the fly.
+7
source share
2 answers

You want to say

 this(t => { }) 

Think of it this way. You need t => anonymous-expression-body . In this case, anonymous-expression-body is expression or block . You cannot have an empty expression, so you cannot specify an empty method body with expression . Therefore, you need to use block , in which case you can say { } to indicate that a block has an empty statement-list and therefore is an empty body.

For more information, see the grammar description, Appendix B.

And here is another way to think about it that you can use to discover it for yourself. Action<T> is a method that takes T and returns void . You can define an Action<T> using a non-anonymous method or an anonymous method. You are trying to figure out how to do this using an anonymous method (or rather a special anonymous method, namely a lambda expression). If you want to do this using a non-anonymous method, you will say

 private void MyAction<T>(T t) { } 

and then you can say

 this(MyAction) 

which uses the concept of a group of methods. But now you want to translate this into a lambda expression. So, let’s just take the body of the method and make it a lambda expression. Therefore, we throw away private void MyAction<T>(T t) and replace it with t => and literally copy the body of the method { } .

 this(t => { }) 

Boom.

+32
source

Isn't that curly braces?

 public FooClass() : this(o => {}) { } 

Lambda form (/*paramaters*/) => {/*body*}

The brackets around the parameters can be omitted, but braces around the body can be omitted only if this is one (not empty) statement.

+6
source

All Articles