Search code examples
c#methodsextending

How to accept a code block on a method C#


I'm writing an extensions library for C#, and I'm wondering if it's possible to accept code blocks on a method call. Something like below:

foo()
{
  var bar = 0;
};

Or something like this would also do:

foo(
{
var bar = 0; //As an argument to the method 
});

Solution

  • You can pass in a delegate/lambda to accomplish this.

    public void foo(Action del)
    {
        var local = del;
        if (local != null)
        {
            local();
        }
    }
    
    foo(() => 
    {
    var bar = 0;
    });
    

    You can read more here