0

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 
});
TechnicalTophat
  • 1,655
  • 1
  • 15
  • 37

1 Answers1

0

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

David Pilkington
  • 13,528
  • 3
  • 41
  • 73