1

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

Fanfarone
  • 131
  • 1
  • 7
  • Does this answer your question? [C# Passing Function as Argument](https://stackoverflow.com/questions/3622160/c-sharp-passing-function-as-argument) – Xaqron Nov 30 '19 at 12:38
  • Something here does not add up. You want to start the same - not similar but the **same** Method in several times? No different Argument? No collection of Functions? Or is this just an example to figure out how to do it with 1? – Christopher Nov 30 '19 at 12:59

1 Answers1

2

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.

Sweeper
  • 213,210
  • 22
  • 193
  • 313