C# Quiz: Will that compile? [Answer]

Some good comments on my recent quiz. Many of you are hitting on the right thing…

The answer is no, this will not compile as is. This is because in V2.0 we added a new constructor to Thread that allows you to pass a ParameterizedThreadStart delegate.

Jay responded to the thread with several good fixes…

  1. Be explicit about the parameter list:

 

            new Thread(delegate () { Console.WriteLine("On another thread"); }).Start();

 

  1. Select the overload & delegate type via casting:

 

            new Thread((ParameterizedThreadStart) delegate { Console.WriteLine("On another thread"); }).Start();

 

  1. Explicitly create a delegate instance:

 

new Thread(new ParameterizedThreadStart(delegate { Console.WriteLine("On another thread"); })).Start();

 

  1. Use a local temp:

 

            ParameterizedThreadStart start = delegate { Console.WriteLine("On another thread"); };

            new Thread(start).Start();

 

  1. Don’t use an anonymous method:

 

            new Thread(MyThreadStart).Start();

        }

        static void MyThreadStart(object obj)

        {

            Console.WriteLine("On another thread");

        }

 

 

What do you think the “best” solution is? Clearly VS could be a little more helpful in writing this kind of code… what sort of VS support would you suggest?