0

Let's say I had a method that took a delegate as a parameter, like this:

public delegate void SampleDelegate(int foo);

public void DoSomething(SampleDelegate del) 
{
    //Does something
}

Would there be a shorthand for doing something like this?

static void Main(String[] args)
{
    void bar(int foo) {
        int x = foo;
    } 
    DoSomething(bar);
}

Or is this the most efficient way to do this?

Ideally, I would do something like this:

static void Main(String[] args)
{
    DoSomething(void(int foo) {
        int x = foo;
    });
}

but that generates syntax errors. Is there a proper syntax for doing something like the above?

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
tobahhh
  • 369
  • 1
  • 3
  • 10

1 Answers1

2

You can use a lambda expression to create a function as an expression:

DoSomething(myInt => { ... });

You don't need to declare SampleDelegate either. You can use Action<int>.

usr
  • 168,620
  • 35
  • 240
  • 369