views:

348

answers:

3

Can't I have an anonymous delegate declaration, something similar to the following:

    ThreadStart starter = delegate() { go(); };
            ...

    static void go()
    {
      Console.WriteLine("Nice Work");
    }

   // (or)

   ThreadStart starter=delegate() { Console.WriteLine("Hello");}
+1  A: 

Yes, you can. Whats the actual question?

By the way, you're missing a semicolon at the end of your second example:

ThreadStart starter=delegate() { Console.WriteLine("Hello");}

should be:

ThreadStart starter = delegate { Console.WriteLine("Hello"); };

Though the spacing I added is personal choice.

nasufara
those declaration shows error
Whats the error, exactly?
nasufara
can't convert anonymous method to type ThreadStart
+1  A: 

You can skip the ThreadStart. This should work.

Thread t = new Thread(() => 
{
  Console.WriteLine("Hello!");
});
Jesper Palm
Got a feeling that we're dealing with an older .net version here. In that case, this won't work.
Jesper Palm
Thank you very much
+1  A: 

What error do you get? Missing semicolon? This compiles for me.

    static void go()
    {
        Console.WriteLine("Nice Work");
    }

    public void Run()
    {
        ThreadStart starter1 = delegate() { go(); };

        ThreadStart starter2 = delegate() { Console.WriteLine("Hello");};

        ThreadStart starter3 = () =>  Console.WriteLine("Hello");

    }
Cheeso
can not convert anaonymous method to type ThreadStart. I m using ASp.NET 3.5 and C# 3.0. Just compiling the same example provided by you.
have you included `using System.Threading` ? Is there any other text in that error message?
Cheeso
As you said i missed semicolon,now it is fine.Thank you a lot.
Thank you once again