HOW TO: Passing a function

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Hello,

Thanks for reviewing my question. I am coming from a C++ background and would like to know how do you pass a function as a parameter to a function in C#? I am assume you must use a delegate.

void Func( (void *)() fn )
{
fn();
}

void Func2() {}

void main()
{
Func( Func2);
}

Many Thanks
Peter
 
Peter said:
Thanks for reviewing my question. I am coming from a C++ background
and would like to know how do you pass a function as a parameter to a
function in C#? I am assume you must use a delegate.

Indeed.

For example:

using System;

class Test
{
delegate void Function();

static void ExecuteFunction (Function foo)
{
foo();
}

static void Main()
{
ExecuteFunction (new Function(PrintHello));
}

static void PrintHello()
{
Console.WriteLine ("Hello");
}
}
 
Back
Top