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)
- {
-
- Console.WriteLine($"FirstWorkPerformed Executed and result is: {x + y}");
- }
Using Anonymous Method - SomeActionPerformedHandler mycustomdelegate2 = delegate (int x, int y)
- { Console.WriteLine($"SecondWorkPerformed Executed and result is: {x + y}"); };
Complete Code
- class AnonymousMethodExample
- {
- public delegate void SomeActionPerformedHandler(int x, int y);
- static void Main(string[] args)
- {
-
- SomeActionPerformedHandler mycustomdelegate1 = new SomeActionPerformedHandler(FirstWorkPerformed);
-
- SomeActionPerformedHandler mycustomdelegate2 = delegate(int x, int y)
- {
- Console.WriteLine($ "SecondWorkPerformed Executed and result is: {x + y}");
- };
- }
- public static void FirstWorkPerformed(int x, int y)
- {
-
- Console.WriteLine($ "FirstWorkPerformed Executed and result is: {x + y}");
- }
- }
These are the following benefits of the anonymous method:
- 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();
- }
- }
In the above example we are specifying a code block instead of a delegate so it creates a thread and contains the code that executes without creating an additional method for the delegate.
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();
- }
- }
Output 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
- {
-
-
-
- [ComVisible(true)]
- public delegate void ThreadStart();
- }
There are a lot of in-built delegates in C#.
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));
Complete code - class AnonymousMethodExample
- {
- public delegate void SomeActionPerformedHandler(int x, int y);
- static void Main(string[] args)
- {
- StartNewThread(newThreadStart(PrintCurrentTime));
- StartNewThread(PrintCurrentTime);
- }
- static void StartNewThread(ThreadStart threadStart)
- {
- threadStart();
- }
- static void PrintCurrentTime()
- {
- Console.WriteLine($ "Current DateTime is : {DateTime.Now}");
- Thread.Sleep(1000);
- PrintCurrentTime();
- }
- }
Example 2:
using - this.button1.Click += this.button1_Click;
instead of - this.button1.Click += new System.EventHandler(this.button1_Click);
And the compiler will infer the delegate internally.
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)
- {
-
- SomeActionPerformedHandler mycustomdelegate1 = new SomeActionPerformedHandler(FirstWorkPerformed);
-
- SomeActionPerformedHandler mycustomdelegate2 = delegate(int x, int y)
- {
- Console.WriteLine($ "SecondWorkPerformed Executed and result is: {x + y}");
- };
-
- SomeActionPerformedHandler mycustomdelegate3 = (x, y) =>
- {
- Console.WriteLine($ "ThirdWorkPerformed Executed and result is: {x + y}");
- };
- }
- public static void FirstWorkPerformed(int x, int y)
- {
-
- System.Threading.Thread.Sleep(500);
- Console.WriteLine($ "FirstWorkPerformed Executed and result is: {x + y}");
- }
- }
You may be thinking that if the lambda expression has been introduced, then why will we need to use named method or anonymous method for associating method with delegate? I would like to clarify that no one is a replacement of any other, all three are the ways to call delegates and they have their own importance.
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:
-
- SomeActionPerformedHandler mycustomdelegate1 = delegate
- {
- Console.WriteLine($ "FirstWorkPerformed Executed");
- };
- mycustomdelegate1.Invoke(10, 20);
Complete code: - classProgram
- {
- publicdelegatevoidSomeActionPerformedHandler(int x, int y);
- staticvoid Main(string[] args)
- {
-
- SomeActionPerformedHandler mycustomdelegate1 = delegate
- {
- Console.WriteLine($ "FirstWorkPerformed Executed");
- };
- mycustomdelegate1.Invoke(10, 20);
- }
- }
- But the same thing will not work with lambda expression.
-
- SomeActionPerformedHandler mycustomdelegate2 = () =>
- {
- Console.WriteLine($ "SecondWorkPerformed Executed and result is: {x + y}");
- };
It will throw the following complete time error:
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#.