In this article I will explain about delegates with named method, anonymous method, Lambda Expression, anonymous method with omit parameter list, and delegate inference.

This is my 2nd article on “understanding delegates in C#” and in this article I will explain about those points of delegates which were not covered in the previous article. If you missed the previous article on understanding delegates in C# you can go through the following link:
In my previous article I explained about Event, Event Raiser, Event Handler, Delegate, EventArgs (event data), Delegates, and Event Handling with Windows Form, WPF and Web Form Applications, Singlecast and Multicast delegate, way of calling a delegate (using Invoke method, by passing it as parameter, by passing parameters inside the delegate object) using return type other than void with Multicast delegates, adding methods in invocation list and removing it from invocation list and calling it, etc.
In this article I will explain these points:
- Instantiate the delegate using an anonymous method.
- Delegate inference.
- Instantiate the delegate using Lambda Expression.
- Instantiate the delegate using an anonymous method & omit parameter list.
Instantiate the delegate using an anonymous method
We have already seen a lot of ways to instantiate the delegate using named method. Now let us see how the same thing can be used with anonymous method.
The delegate feature was available in C# from the first day of its release but later on a lot of updates were done in later versions. In C# 2.0 a new way of calling method using delegate has been introduced which is known as anonymous method.
As it has the name anonymous it means it does not have a method name, and creating anonymous methods is essentially a way to pass a code block as a delegate parameter.
Using Named Method
- SomeActionPerformedHandler mycustomdelegate1 = new SomeActionPerformedHandler(FirstWorkPerformed);
- public static void FirstWorkPerformed(int x, int y)
- {
- //do something for FirstWorkPerformed
- Console.WriteLine($"FirstWorkPerformed Executed and result is: {x + y}");
- }
- SomeActionPerformedHandler mycustomdelegate2 = delegate (int x, int y)
- { Console.WriteLine($"SecondWorkPerformed Executed and result is: {x + y}"); };
- class AnonymousMethodExample
- {
- public delegate void SomeActionPerformedHandler(int x, int y);
- static void Main(string[] args)
- {
- // Instantiate the delegate using named Method
- SomeActionPerformedHandler mycustomdelegate1 = new SomeActionPerformedHandler(FirstWorkPerformed);
- // Instantiate the delegate using an anonymous method
- SomeActionPerformedHandler mycustomdelegate2 = delegate(int x, int y)
- {
- Console.WriteLine($ "SecondWorkPerformed Executed and result is: {x + y}");
- };
- }
- public static void FirstWorkPerformed(int x, int y)
- {
- //do something for FirstWorkPerformed
- Console.WriteLine($ "FirstWorkPerformed Executed and result is: {x + y}");
- }
- }
- We do not have to create a separate method in the case of the anonymous method due to the fact that it reduces the coding overhead in instantiating delegate.
- We can omit the parameter list while using the anonymous method.
You may be thinking that when you have the advantage of specifying a code block instead of a delegate it can be useful. It can be useful in many cases. Suppose you have to start a new thread, so in that case why would you prefer to create a new method to start the thread? Just use it with the anonymous method.
Example
- publicstaticvoid StartNewThreadToWriteConsoleMsg()
- {
- Thread thread = newThread(delegate()
- {
- System.Console.WriteLine("Hi!!!");
- System.Console.WriteLine("Good Morning everyone");
- System.Console.WriteLine("Welcome to understanding delegates in C#");
- });
- thread.Start();
- }
- Complete code: classAnonymousMethodExample
- {
- staticvoid Main(string[] args)
- {
- StartNewThreadToWriteConsoleMsg();
- }
- publicstaticvoid StartNewThreadToWriteConsoleMsg()
- {
- Thread thread = newThread(delegate()
- {
- System.Console.WriteLine("Hi!!!");
- System.Console.WriteLine("Good Morning everyone");
- System.Console.WriteLine("Welcome to understanding delegates in C#");
- });
- thread.Start();
- }
- }
I am giving an example to create a thread using the anonymous method, but we also have another option to create a thread. Let’s see another way to create a thread using delegate ThreadStart.
Code
- static void StartNewThread(ThreadStart threadStart)
- {
- threadStart();
- }
- static void PrintCurrentTime()
- {
- Console.WriteLine($ "Current DateTime is : {DateTime.Now}");
- Thread.Sleep(1000);
- PrintCurrentTime();
- }
- And call it as: StartNewThread(newThreadStart(PrintCurrentTime));
- Complete Code: classAnonymousMethodExample
- {
- public delegate void SomeActionPerformedHandler(int x, int y);
- staticvoid Main(string[] args)
- {
- StartNewThread(newThreadStart(PrintCurrentTime));
- }
- staticvoid StartNewThread(ThreadStart threadStart)
- {
- threadStart();
- }
- staticvoid PrintCurrentTime()
- {
- Console.WriteLine($ "Current DateTime is : {DateTime.Now}");
- Thread.Sleep(1000);
- PrintCurrentTime();
- }
- }

Here you may be thinking that we have not used the delegate keyword. I am not using any delegate keyword but rather using the in-built delegate of C#. If you press F12 (go to definition) on ThreadStart then you will find the following definition:
- namespace System.Threading
- {
- //
- // Summary:
- // Represents the method that executes on a System.Threading.Thread.
- [ComVisible(true)]
- public delegate void ThreadStart();
- }
Delegate inference
Delegate inference means attaching a method directly with the event or passing a method reference directly and the compiler will infer the delegate internally.
Example 1:
Using
- StartNewThread(PrintCurrentTime);
- Instead of
- StartNewThread(newThreadStart(PrintCurrentTime));
- class AnonymousMethodExample
- {
- public delegate void SomeActionPerformedHandler(int x, int y);
- static void Main(string[] args)
- {
- StartNewThread(newThreadStart(PrintCurrentTime)); //comment and use below line you will get the same result.
- StartNewThread(PrintCurrentTime);
- }
- static void StartNewThread(ThreadStart threadStart)
- {
- threadStart();
- }
- static void PrintCurrentTime()
- {
- Console.WriteLine($ "Current DateTime is : {DateTime.Now}");
- Thread.Sleep(1000);
- PrintCurrentTime();
- }
- }
using
- this.button1.Click += this.button1_Click;
- this.button1.Click += new System.EventHandler(this.button1_Click);
Instantiate the delegate using Lambda Expression
In C# 3.0 Lambda expression has been introduced which provides features to write very little code to associate a method with a delegate, so the user has more options on using lambda expressions. So we can say that lambda expressions supersede anonymous methods as the preferred way to write inline code.
Example:
- public delegate void SomeActionPerformedHandler(int x, int y);
- SomeActionPerformedHandler mycustomdelegate3 = (x, y) =>
- {
- Console.WriteLine($ "ThirdWorkPerformed Executed and result is: {x + y}");
- };
- Complete Code: classProgram
- {
- public delegate void SomeActionPerformedHandler(int x, int y);
- static void Main(string[] args)
- {
- // Instantiate the delegate using named Method
- SomeActionPerformedHandler mycustomdelegate1 = new SomeActionPerformedHandler(FirstWorkPerformed);
- // Instantiate the delegate using an anonymous method
- SomeActionPerformedHandler mycustomdelegate2 = delegate(int x, int y)
- {
- Console.WriteLine($ "SecondWorkPerformed Executed and result is: {x + y}");
- };
- // Instantiate the delegate using Lambda Expression
- SomeActionPerformedHandler mycustomdelegate3 = (x, y) =>
- {
- Console.WriteLine($ "ThirdWorkPerformed Executed and result is: {x + y}");
- };
- }
- public static void FirstWorkPerformed(int x, int y)
- {
- //do something for FirstWorkPerformed
- System.Threading.Thread.Sleep(500);
- Console.WriteLine($ "FirstWorkPerformed Executed and result is: {x + y}");
- }
- }
For instance, anonymous method provides the features that we can omit the parameter list but we cannot do this with lambda expression.
Instantiate the delegate using an anonymous method & omit parameter list
Example:
- // Instantiate the delegate using an anonymous method & omit parameter list
- SomeActionPerformedHandler mycustomdelegate1 = delegate
- {
- Console.WriteLine($ "FirstWorkPerformed Executed");
- };
- mycustomdelegate1.Invoke(10, 20);
- classProgram
- {
- publicdelegatevoidSomeActionPerformedHandler(int x, int y);
- staticvoid Main(string[] args)
- {
- // Instantiate the delegate using an anonymous method & omit parameter list
- SomeActionPerformedHandler mycustomdelegate1 = delegate
- {
- Console.WriteLine($ "FirstWorkPerformed Executed");
- };
- mycustomdelegate1.Invoke(10, 20);
- }
- }
- But the same thing will not work with lambda expression.
- //try with lambda expression
- SomeActionPerformedHandler mycustomdelegate2 = () =>
- {
- Console.WriteLine($ "SecondWorkPerformed Executed and result is: {x + y}");
- };
Error CS1593 Delegate 'Program.SomeActionPerformedHandler' does not take 0 arguments ParameterOmitWithAnonymousMethod

In this article I have explained about instantiating delegate using an anonymous method, delegate inference, etc.
Instantiate the delegate using Lambda Expression & instantiate the delegate using an anonymous method & omit parameter list. In the next article I will explain about in-built delegates of C#.

Banketeshvar NarayanPosted Mar 26, 2016, 10:26 AM
Thanks to all the readers for giving your precious time to read this article & thanks once again for your valuable comments.
Ehsan SajjadPosted Jan 11, 2016, 10:27 AM
Nicely written
Ankit SaxenaPosted Jan 11, 2016, 8:38 AM
Good informative post. Thanks for sharing.
Ankit BansalPosted Jan 11, 2016, 1:43 AM
Nice...keep sharing..
Raja TPosted Jan 10, 2016, 11:10 PM
Nice, Thanks for sharing
Ankur MistryPosted Jan 10, 2016, 1:03 PM
Nice share Banketeshvar Narayan
Santhakumar MunuswamyPosted Jan 10, 2016, 11:22 AM
Thanks for nice article