Pass a function as an argument

  • Thread starter Magnus.Moraberg
  • Start date
M

Magnus.Moraberg

Hi,

I have a function within which I would like to call another function.
Id like to pass the second function into the first as an argument. As
follows:

Function1(Function2a);
Function1(Function2b);

void Function1(? Function2)
{
Function2();
}

Is this possible?

Thanks,

Barry.
 
H

Hans Kesting

(e-mail address removed) brought next idea :
Hi,

I have a function within which I would like to call another function.
Id like to pass the second function into the first as an argument. As
follows:

Function1(Function2a);
Function1(Function2b);

void Function1(? Function2)
{
Function2();
}

Is this possible?

Thanks,

Barry.

Yes, it's called a "delegate".

There are several ways, see forinstance
http://gregorybeamer.spaces.live.com/blog/cns!B036196EAF9B34A8!542.entry

Hans Kesting
 
M

Marc Gravell

Yes; what you are talking about is a delegate; simply declare (or
re-use) a suitable delegate type (i.e. with matching args and return
type). If you just want to call a method, then Action, MethodInvoker or
ThreadStart should suffice.

Marc

using System;
static class Program
{
static void Main()
{
Function1(Function2a);
Function1(Function2b);
}
static void Function2a()
{
Console.WriteLine("2a");
}
static void Function2b()
{
Console.WriteLine("2b");
}
static void Function1(Action Function2)
{
Function2();
}
}
 
J

Jon Skeet [C# MVP]

I have a function within which I would like to call another function.
Id like to pass the second function into the first as an argument.

As mentioned by everyone else too, what you're after is a delegate.

If you've done any Windows Forms programming, you've already used
delegates, perhaps without knowing it. Any time you wire up an event,
you're using a delegate.

See http://pobox.com/~skeet/csharp/events.html for more on this.

Jon
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top