2

When working with existing frameworks, sometimes you need to pass in an action delegate which performs no action usually an extension point added by the original developer. Example:

var anObject = new Foo(() => { });

And presumably the Foo object will call this delegate at some time. My goal here is to eliminate the use of { }, because my style dictates that { } need to be on their own, and separate lines, and I'm a bit OCD and hate being verbose if I don't have to be.

When dealing with an action which returns a value, this is simple enough- you can provide an expression instead of a statement (thus eliminating the braces.) Example:

var anObject = new Foo(() => string.Empty);

So, I suppose the question is two parts...

Does .NET have any sort of default empty action? Is there syntactic sugar for providing an empty expression to a lambda, other than { }?

The current solution I'm leaning towards is to define the delegate in a preceding assignment to avoid having to use the lambda expressing inside a function invocation.

VV5198722
  • 374
  • 5
  • 19
Sprague
  • 1,610
  • 10
  • 22
  • Does this answer your question? [Is there a way to specify an "empty" C# lambda expression?](https://stackoverflow.com/questions/1743013/is-there-a-way-to-specify-an-empty-c-sharp-lambda-expression) – Michael Freidgeim Jul 29 '21 at 08:56

1 Answers1

2

There's nothing built-in that I'm aware of.

You could just define the delegate once as a helper singleton:

var anObject = new Foo(NoOpAction.Instance);

// ...

var anotherObject = new Bar(NoOpAction.Instance);

// ...

public static class NoOpAction
{
    private static readonly Action _instance = () => {};

    public static Action Instance
    {
        get { return _instance; }
    }
}

And because you're handed exactly the same delegate every time you use NoOpAction.Instance throughout your program, you're also saving on the (admittedly small) cost of creating and garbage-collecting multiple delegates that all do the same thing.

LukeH
  • 263,068
  • 57
  • 365
  • 409
  • This is the direction I was headed! Unfortunately, the code I'm working with uses typed delegates, but yours is about as close as it gets. Thanks. (The typed delegate problem wasn't clear to me until after asking this question) – Sprague Mar 26 '13 at 11:40
  • @Sprague, looks like you need `public static class NoOpAction`, and `public static class NoOpAction`... only another 14 more to go! – Nigel Touch Apr 07 '16 at 11:46