Quick and dirty example of using Delegate, Func and Action
side by side in C# to show how to use function pointer or callback in C#
Example #1 Delegate and Func side by side
static int DoubleTheValue(int x)
{
return x * 2;
}
// delegate type should match the function signature - DoubleTheValue
public delegate int functionDelegateType(int x);
static void Method1(functionDelegateType func)
{
int doubleValue = func(5);
}
static void Method2(Func<int, int> func) // easier syntax
{
int doubleValue = func(5);
}
static void Main(string[] args)
{
Method1(DoubleTheValue);
Method2(DoubleTheValue);
}
Example #2 Delegate and Action side by side
static void DisplayOnConsole(int x)
{
Console.WriteLine(x.ToString());
}
// delegate type should match the function signature - DisplayOnConsole
public delegate void functionDelegateType (int x);
static void Method1(functionDelegateType func)
{
func(5);
}
static void Method2(Action<int> func) // easier syntax
{
func(5);
}
static void Main(string[] args)
{
Method1(DisplayOnConsole);
Method2(DisplayOnConsole);
}
Reference:
https://social.msdn.microsoft.com/Forums/vstudio/en-US/a1ac99ed-0801-4773-a866-4223d42422cf/how-to-pass-function-as-an-argument-to-another-function-in-c?forum=csharpgeneral
side by side in C# to show how to use function pointer or callback in C#
Example #1 Delegate and Func side by side
static int DoubleTheValue(int x)
{
return x * 2;
}
// delegate type should match the function signature - DoubleTheValue
public delegate int functionDelegateType(int x);
static void Method1(functionDelegateType func)
{
int doubleValue = func(5);
}
static void Method2(Func<int, int> func) // easier syntax
{
int doubleValue = func(5);
}
static void Main(string[] args)
{
Method1(DoubleTheValue);
Method2(DoubleTheValue);
}
Example #2 Delegate and Action side by side
static void DisplayOnConsole(int x)
{
Console.WriteLine(x.ToString());
}
// delegate type should match the function signature - DisplayOnConsole
public delegate void functionDelegateType (int x);
static void Method1(functionDelegateType func)
{
func(5);
}
static void Method2(Action<int> func) // easier syntax
{
func(5);
}
static void Main(string[] args)
{
Method1(DisplayOnConsole);
Method2(DisplayOnConsole);
}
Reference:
https://social.msdn.microsoft.com/Forums/vstudio/en-US/a1ac99ed-0801-4773-a866-4223d42422cf/how-to-pass-function-as-an-argument-to-another-function-in-c?forum=csharpgeneral
0 comments :
Post a Comment