Anonymous Methods and delegates

This topic is quite a common topic on the net after c# 2.0 has been released. ( quite  a fews months before) . With the introduction of c# 2.0 came in the concept of Anonymous methods and Anonymous delegates. Delegates , previously needed o have named methods to point to. With this new introduction , adds another flexibilty.... The code snippet below shows both ways ( the named method and the anonymous way)

class Program

{

delegate void TestAnonDelegate(string foo);

static void Main(string[] args)

{

//delegate instatiation --the old way

TestAnonDelegate O = new TestAnonDelegate(DoWork);

O("In method do work");

//delegate instatiation --the new way

TestAnonDelegate t = delegate(string foo) { Console.WriteLine(foo); Console.ReadKey(); }; 

// note that the delegate keyword is used

t("in anonymous delegate");

}

static void DoWork(string s)

{

Console.WriteLine(s);

Console.ReadKey();

}

}

Both do the same job but ne with a named method from beforehand and one without. There are some limitations that I know of anonymous delegates . They are...

i) they cannot access out,ref parameters of a oute scope.

ii) no break,continue,goto is allowd within anonymous methods

 

If u know of any other limitations , do post me a comment

Cheers................

 

  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati
Print | posted on Thursday, November 16, 2006 5:24 AM

Feedback

# re: Anonymous Methods and delegates

left by Shubhajyoti at 2/13/2007 4:58 AM Gravatar
good example
Post A Comment
Title:
Name:
Email:
Website:
Comment:
Verification: