C# Delegates and Events—Anonymous methods
Microsoft .NET Framework, ASP.NET, Visual C# (CSharp, C Sharp, C-Sharp) Developer Training, Visual Studio
| CSharp-Online.NET:Articles |
| C# Articles |
|
| edit |
Anonymous methods
One thing you should consider about the Multithreaded example from the previous section is that the ThreadProc method is never invoked directly from the source code. Instead, the Thread object calls it through the ThreadStart delegate as a result of our call to the Thread object’s Start method. An astute programmer might wonder why we should bother having this ThreadProc method, since we are not calling it anyway. Wouldn’t it be a better design and more efficient to avoid having extra methods lying around? With that in mind, I introduce one of my favorite features of .NET version 2.0—anonymous methods.
An anonymous method is a block of code passed to the delegate at creation time. Since these blocks of code do not have method names, they can not be called, except through the delegate. You no longer have those useless methods lying around.
The following example shows the GreetingDelegate that we defined earlier, this time being instantiated with an anonymous method.
class DelegateDemo { delegate void GreetingDelegate(string s); static void Main(string[] args) { // use an anonymous method for the delegate GreetingDelegate gd = delegate(string s) { Console.WriteLine(s); } // invoke the delegate gd("Hello"); } }
The GreetingDelegate is declared as it was before. The interesting part is inside of the Main method when the GreetingDelegate is instantiated with an anonymous method. The syntax might take a minute to get used to. The delegate keyword is followed by the parameter list that the delegate will accept. The parameter list is then followed by the block of code for the anonymous method. As before, the final line of the Main method invokes the anonymous method through the delegate instance.
Now, let’s rewrite our thread example to use an anonymous method.
class DelegateDemo { static void Main(string[] args) { Thread t = new Thread(delegate() { // do some thread work CalculatePrimes(); }); t.Start(); t.Join(); } }
The ThreadStart delegate passed to the Thread constructor has been created with an anonymous method. Since ThreadStart accepts no parameters, the parentheses following the delegate keyword are empty. Notice that the bracket that closes the anonymous method’s body is inside of the closing parenthesis of the Thread constructor call.
|

