Learn C# Part 6: Delegates - Lambda Expression, Expression Tree, Func<>, Action<> and Predicate<>

Ahteshamax
Posted by in C# category on for Beginner level | Points: 250 | Views : 897 red flag

In this article we will discuss about four fundamentals of delegates lambda expression, Func<>, Action<> and Predicate.
Recommendation
Read Learn C# Part 5: Mini project - File Search. before this article.

Below are the links for other articles of Learn C# Step by Step :-

Learn C# Step By Step :- Part 1.

Learn C# Step By Step: - Part 2

Learn C# Step By Step (Concept of Class and Object): - Part 3

Learn C# Part 4: Synchronous and Asynchronous methodology.

Learn C# Part 4b: Delegates, Multicast Delegates and Events.

Learn C# Part 5: Mini project - File Search.

In this article we will learn four important fundamentals of C# language and how to use each of them. First is the Lambda expression which is used to create delegates and expression tree. Remaining other three readymade delegates are Action<> delegate, Func<> delegate, Predicate<> delegate. Also we will see an example of anonymous methods.


The whole purpose of these four delegates is that it will make delegate code simpler and shorter. Writing code of each, working style and output given is different. While with lambda expression you can create expression trees. Use of more expression trees is in LINQ, Business Language (BL). Following in this article we see demonstrate practically for all four delegates.

The whole purpose of these four delegates is that it will make delegate code simpler and shorter. Writing code of each, working style and output given is different. While with lambda expression you can create expression trees. Use of more expression trees is in LINQ, Business Language (BL). Following in this article we see demonstrate practically for all four delegates.

Delegate

Below is the simple code written for traditional delegate where we have declared a delegate “pointerCalArea” and having a pointer name “calpointer” which will perform area calculation when value of radius “rad” is given. Finally invoke the program.


Now instead of viewing output on console prompt we will put a debug point in the program and see output generated.

1) Put a debug point on code line double Area = calpointer.Invoke(20); as shown in the image down below.

2) Press F5 on the keyboard or click on “Start” option available in the Menu which will now show line in red color on which debug point has inserted.

3) Press Stepover button on Menu bar or press F10 on keyboard as shown in the image down below.

4) Now hover the mouse over the “Area” text on the line where earlier we have put the debug point.

5) You will see output calculated as Area = 1256


So this was the traditional way of writing delegate and we have also see new way of viewing output using debug point.

Anonymous methods

Next we will see delegate code writing using anonymous methods prior to start using lambda expression and shorten our code by removing the function called Calculate area from existing Delegate program.

1) Comment or remove existing code of pointer attaching with “CalculateArea” method as this method will be no longer used.

2) Write an inline delegate code under Main method with passing parameter “int rad” along with area calculation as shown in the image down below.

3) Comment or remove existing method “CalculateArea”.

4) Declare a variable “Area” with data type as “double” and invoke pointer with “rad” value, rad = 20.


Next is rebuild the solution and put debug point before running application to see the output on variable “Area” when mouse is hovered on it.

Now run the application by pressing F5 on the keyboard or click on “Start” on the Menu bar of Visual Studio then press F10 or step over button on the menu bar as shown in the image down below and see the output by hovering mouse “1256” over “Area” variable.


We have demonstrated example delegate with anonymous methods by eliminating separate method. Next we will see example using lambda expression.

Lambda expression

Lambda expression is a simple inline code which is denoted by symbol “=>”. Code of the lambda expression are divided into two parts: -

(a) create a pointer of delegate declared first by declaring input parameters through a variable and

(b) second is the inline code.

Making it simpler we will use lambda expression code in our example

pointerCalArea calpointer = rad => 3.14 * rad * rad;

Lambda expression is very much intelligent by looking at the inline code it understands that “rad” is a variable and its datatype can be of “double”.

Followed by a line to invoke the pointer by mentioning the values as we did it earlier as shown in the image down below.

Rebuilt the solution and place debug point on the lambda expression and run the application by clicking Start button the menu bar or by pressing F5 on keyboard. Next is either click on step over button available on menu bar or press F10 on keyboard to move the program. When press twice on F10 or stepover button on the menu bar and now if you hover the mouse you will get to see the output on Area variable as shown in the image down below: -


Time is to now move on with other fundamental part of delegate. We will see into generic delegate with lambda expression and its coding done on Visual Studio.

Func<> delegate

Func<> delegate is a generic readymade delegate. It takes up any input and given output for that just you have to define input and output datatypes.


In our example we have used input datatype as “double” & output delegate as “double”. From below image shown after “Func” keyword first “Double” datatype is input and second “Double” datatype output.


With the use of lambda + Func<> in our application inline code has reduced even more. Now we will put a debug point on the expression line where Func<> and lambda expression is present. After the application is executed click on step over button available under menu bar or by clicking F10 twice on the keyboard you will be able to see the output on the “Area” variable as our application is running in debug mode.


Action<> delegate

There are scenarios where we take input but do not produce any output over here only action takes place. Action<> delegate takes up any input but do not return any output rather it return type uses ‘’void” and if used then can only be used to display out something as an action.


So in our existing code we will introduce “Action<>” keyword which takes input and display’s output on the console prompt as “My Action Displayed”.

Here is the inline code which we have to write with Action keyword and string keyword with pointer name “OurAction” and declaring “Act” as variable. Inline code which will display code on console prompt.

Action OurAction = Act => Console.Write(Act);

Invoke pointer with the text to display on console prompt “My Action Displayed”.

OurAction(“My Action Displayed”);

Rebuilt the solution and place debug point on the lambda expression and run the application by clicking Start button on the menu bar or by pressing F5 on keyboard. Next is either click on step over button available on menu bar or press F10 on keyboard to move the program. When press twice on F10 or stepover button now on console prompt you will see the output displayed as shown in the figure down below.


Predicate<> delegate

It is an extension and special kind to Func<> delegate which is used for doing comparison. It will take any input but the output produced would be Boolean returning type as “true” or “false”.


To simplify learning of this Predicate<> delegate we will consider an example which will check length of the output text if it is less than 9 then it will return output result as “True” or else “False”. As condition return result and Predicate<> delegate will attach Boolean to that comparison result and finally shows result as “True” or “False”.

Below is the line of code which has to written on Visual Studio. Starting with Predicate keyword and defining datatype as string with pointer name as “CheckLessThan9” followed by variable name “z” finally an inline code with comparison statement which checks variable length less than 9 or not.

Predicate CheckLessThan9 = z => z.Length < 9;

Then as usual which we did for other delegate we will invoke pointer “CheckLessThan9” by giving the value to pointer whose length will be checked, here value given in text is “RonniePinto”.

Console.Write(CheckLessThan9(“RonniePinto”));

Rebuilt the solution and place debug point on the lambda expression and run the application by clicking Start button the menu bar or by pressing F5 on keyboard. Next is either click on step over button available on menu bar or press F10 on keyboard to move the program. When press twice on F10 or stepover button now on console prompt you will see the output displayed as “False”. Value of the variable text “RonniePinto” has total length 11 is greater than 9 and it fails to satisfy the comparison inline statement.


Expression Tree

Whenever performing calculation for an expression if we go with traditional way then we have to use lots of IF conditions, some collections or some customized logic in order to achieve output. Other way is to use expression tree and get achieved result with a single inline code.

In order to understand expression tree with an example let us consider following example where we have c1 = (20 + 30) and c2 = (8 + 9) and where to calculate c3 = c1 – c2.

We will first calculate by doing addition the equation of c1 = 20 + 30 = 50 then adding c2 = 8 + 9 = 11 and finally subtracting “c3” which is “c1 – c2”, output comes to 33.


Now we will write coding of expression on Visual Studio with the below mentioned steps: -

1) In order to do coding for expression tree we have to first import namespace for expression using the following syntax

using System.Linq.Expressions;

2) Create first part of left side expression for expression tree which will do addition of c1 = (20 + 30). So syntax would be a binary expression “c1” which will do addition of binary constant variable 20 & 30.

BinaryExpression c1 = Expression.MakeBinary(ExpressionType.Add, 
                                                        Expression.Constant(20), 
                                                        Expression.Constant(30));

3) Next we will create expression for right side, as binary expression “c2” and expression binary type “Add” with expression constant as 8 & 9. Here is the equation c2 = (8 + 9)

BinaryExpression c1 = Expression.MakeBinary(ExpressionType.Add, 
                                                        Expression.Constant(8), 
                                                        Expression.Constant(9));

4) As addition part within the brackets have been completed now we will do final part of expression which is subtraction so output received at “c1” and “c2” will be subtracted to give final output “c3” of expression tree. Here is the equation c3 = c1 – c2

BinaryExpression c3 = Expression.MakeBinary(ExpressionType.Subtract,
                                                        c1,
                                                        c2);

5) Using expression tree create a lambda expression and invoke it. To evaluate expression tree create lambda expression by writing "Expression.Lambda" and expecting a delegate type "Func" which will return an integer "int" in the variable "output". When said in the expression "c3.Compile" it will execute by parsing all expression tree, invoke node and evaluate each node finally giving result at "output" variable.

int output = Expression.Lambda>(c3).Compile()();

6) To see the output on the visual studio put a debug point on the lambda expression.

7) Click F5 on keyboard or press “Start” on the menu bar.

8) Click F10 on keyboard or click on stepover icon available in the menu bar to move debug point.

9) To see the output hover the mouse on “output” variable which shows result of the expression is 33. And if the equation is calculated in general then c1 = 20 + 30 = 50 & c2 = 8 + 9 = 17 and the final part c3 = c1 – c2 = 50 – 17 = 33.

Output shown on variable and general calculation produced result matches to “33”. From this we can conclude that expression tree is correct.


Hope that reader of this article have understood fundamentals and practical demonstration of anonymous methods and types of delegates.

Below is the nice video explaining start-up topic for learning C# programming to complete fresher in IT field: -

Page copy protected against web site content infringement by Copyscape

About the Author

Ahteshamax
Full Name: Ahtesham Shaikh
Member Level:
Member Status: Member
Member Since: 10/3/2016 2:36:04 AM
Country: India
Ahtesham Shaikh
http://www.learnmsbitutorials.net/
Hey Friends, Myself Ahtesham a coder, writer & technical supporter for IT world and for my company Questpond. Having 10+ years of experience in microsoft technologies like WCF, WPF, MVC, Sharepoint, AngularJS, MSBI, Excel 2000 - 2013, Powerpoint, C#, SQL Server and so on. I just find myself happy and satisfy by doing this job. Apart from profession love reading novels and other digital network books. I'm a faculty at Questpond and do take trainings on c#, object oriented programming, msbi, sharepoint, mvc, mvc, angularJS and so on. Feel free get in touch me for one-to-one trainings, offline trainings @Andheri Mumbai, Online training via microsoft live meeting.

Login to vote for this post.

Comments or Responses

Posted by: Poynterjeffrey on: 12/1/2016 | Points: 25
Thank you for this wonderful blog. I seen this first time in this blog. It is really interesting. Keep sharing such new information. For academic help visit best essay writing service http://www.buyessays.us

Login to post response

Comment using Facebook(Author doesn't get notification)