How to pass a runnable procedure (a function) as a parameter and run it in C#

2 Answers

0 votes
using System;

class Program
{
    // Define a delegate type for functions that return void
    delegate void FuncDelegate();

    static void Control(FuncDelegate f) {
        f(); // Call the function
    }

    static void Say() {
        Console.WriteLine("abcd");
    }

    static void Main()
    {
        Control(Say); // Pass method reference
    }
}



/*
run:

abcd

*/

 



answered May 21, 2025 by avibootz
0 votes
using System;

class Program
{
    // Generic method that executes a function returning T
    static T Control<T>(Func<T> f) {
        return f();
    }

    static string say() {
        return "abcd";
    }

    static void Main()
    {
        Console.WriteLine(Control(say));
    }
}



/*
run:

abcd

*/

 



answered May 21, 2025 by avibootz
...