Fanfarone
Fanfarone

Reputation: 139

How can I add a method as a parameter of a function

I try to set a method as a parameter but I can't do it. I tried about ten solutions proposed on different topics but it didn't work that's why I create my own topic

public static void startThread(Method methodname (For exemple Class.test))
        {
            for (int i = 1; i <= Xenoris.threads; i++)
            {
                new Thread(new ThreadStart(methodname)).Start();
            }
        }

As you can see I try to do ThreadStart in a function but for that I need to have a method as a parameter which I can't do

To be more precise I want to make my own library and I need to be able to have methods as parameter like: Class.test

I hope someone can help me and I'm sorry for my bad English

Upvotes: 1

Views: 114

Answers (1)

Sweeper
Sweeper

Reputation: 274480

In this case, ThreadStart itself is a delegate, so you could just use that as the parameter type:

public static void startThread(ThreadStart method)
{
    for (int i = 1; i <= Xenoris.threads; i++)
    {
        new Thread(method).Start();
    }
}

And you can directly pass in the name of the method without any parentheses:

startThread(SomeMethod);

Note that the method you pass must be a method that accepts no parameters and returns void.

Upvotes: 2

Related Questions