In versions of C# previous to 2.0, the only way to declare a delegate was to use named methods. C# 2.0 introduces anonymous methods c#.
Creating anonymous methods is essentially a way to pass a code block as a delegate parameter. For example:
// Create a handler for a click event button1.Click += delegate(System.Object o, System.EventArgs e) { System.Windows.Forms.MessageBox.Show("Click!"); };
or
// Create a delegate instance delegate void Del(int x); // Instantiate the delegate using an anonymous method Del d = delegate(int k) { /* ... */ };
By using anonymous methods, you reduce the coding overhead in instantiating delegates by eliminating the need to create a separate method.
For example, specifying a code block in the place of a delegate can be useful in a situation when having to create a method might seem an unnecessary overhead. A good example would be when launching a new thread. This class creates a thread and also contains the code that the thread executes, without the need for creating an additional method for the delegate.
void StartThread() { System.Threading.Thread t1 = new System.Threading.Thread (delegate() { System.Console.Write("Hello, "); System.Console.WriteLine("World!"); }); t1.Start(); }
Creating anonymous methods is essentially a way to pass a code block as a delegate parameter. For example:
// Create a handler for a click event button1.Click += delegate(System.Object o, System.EventArgs e) { System.Windows.Forms.MessageBox.Show("Click!"); };
or
// Create a delegate instance delegate void Del(int x); // Instantiate the delegate using an anonymous method Del d = delegate(int k) { /* ... */ };
By using anonymous methods, you reduce the coding overhead in instantiating delegates by eliminating the need to create a separate method.
For example, specifying a code block in the place of a delegate can be useful in a situation when having to create a method might seem an unnecessary overhead. A good example would be when launching a new thread. This class creates a thread and also contains the code that the thread executes, without the need for creating an additional method for the delegate.
void StartThread() { System.Threading.Thread t1 = new System.Threading.Thread (delegate() { System.Console.Write("Hello, "); System.Console.WriteLine("World!"); }); t1.Start(); }
If you are searching life partner. your searching end with kpmarriage.com. now kpmarriage.com offer free matrimonial website which offer free message, free chat, free view contact information. so register here : kpmarriage.com- Free matrimonial website
0 comments:
Post a Comment