Click here to Skip to main content
Click here to Skip to main content

Tagged as

Anonymous Methods and Lambda Expressions in .NET

, 28 Jul 2014 CPOL
Rate this:
Please Sign up or sign in to vote.
Anonymous methods and lambda expressions in .NET

Introduction

The aim of this article is to provide the basic idea of Anonymous methods and Lambda expressions in C# and Visual Basic.NET.

Anonymous Method

An anonymous method is an unnamed method that contains only body without a name or identifier and it is invoked by the delegates. An anonymous method is referenced or associated with a delegate and it cannot be invoked explicitly or directly without the using of a delegate. The body of anonymous method is surrounded by curly braces and it contains the inline code. The anonymous method is used when we have a small task or operation and we want to perform it inline. An anonymous method is similar to a named method but the main difference is that a named method has a specified name, an access modifier, a return type, a parameters list that contains zero or more parameters, and a body that contains a block of code whereas an anonymous method is an unnamed method that has no name or identifier, no access modifier, and no return type and its declaration always starts from the keyword delegate followed by the parameters list and the method body. The parameters list of an anonymous method may contain zero or more parameters and they are surrounded by small braces. An anonymous method does not need to specify its return type but it allows us to return a value using the return statement. A named method can be invoked directly or explicitly by simply calling its name while an anonymous method cannot be invoked directly or explicitly like a named method but it can be invoked implicitly using a delegate. To invoke an anonymous method, an instance of the delegate is declared and the anonymous method is referenced or associated with it. When an anonymous method is referenced or associated with an instance of the delegate, then we invoke it by calling that instance and pass values to its parameters if it takes parameters. An anonymous method can be referenced or associated with an instance of the delegate by assigning the anonymous method to it as a parameter. When an anonymous method is assigned to an instance of the delegate as a parameter, the instance of the delegate stores its memory address and the method is referenced or associated with it.

A delegate can reference and invoke an anonymous method that has the matching parameters with it. It means that the parameters of the delegate and the parameters of the referenced or associated anonymous method must be the same. For example, if an anonymous method does not take any parameter, then it can be referenced and invoked by an instance of a delegate that does not take any parameter similarly, if an anonymous method takes a single integer parameter, then we must declare an instance of the delegate that takes a single integer parameter and so on. Following is the general syntax to declare a parameter-less anonymous method:

The C# Syntax

instDelegate = delegate() {-Body of the anonymous method-};

Or:

instDelegate = delegate() 
{ 
[-Body of the anonymous Method-] 
};

The VB.NET Syntax

instDelegate = Sub() [-Body of the anonymous method-]

Or:

instDelegate = Sub() 
-------------------------
[-Body of the Anonymous Method-] 
-------------------------
End Sub

In the above declaration, the instDelegate is an instance of the parameter-less delegate that does not take any parameter and it references a parameter-less anonymous method. The [-Body of the Anonymous Method-] indicates the body of the anonymous method that contains the inline code. Following is the general syntax to declare a parameterized anonymous method that takes the specified number of parameters:

The C# Syntax

instDelegate = delegate(ParametersList) {[-Body of Method-]};

Or:

instDelegate = delegate(ParametersList) 
{ 
[-Body of Method-]
};

The VB.NET Syntax

instDelegate = Sub(ParametersList) [-Body of Method-]

Or:

instDelegate = Sub(ParametersList) 
------------------------------------------
[-Body of Method-]
------------------------------------------
End Sub

In the above declaration, the instDelegate is an instance of the parameterized delegate that takes one or more parameters according to the method it references and invokes for example, if the anonymous method takes a single integer parameter, then it must take a single integer parameter, similarly if an anonymous method takes one integer and one float parameter then it must take one integer and one float parameters and so on. The ParametersList indicates a list of parameters of the anonymous method that contains one or more parameters. The [-Body of Method-] indicates the body of the anonymous method that contains the inline code.

Program # 1

Write a program that displays a message on the screen using a parameter-less anonymous method.

The C# Program

using System;

namespace ProgramNamespace
{
//Define a delegate reference type that references or associates a 
//parameter-less anonymous method having no parameters and 
//does not return value

delegate void MyDelegate();

public class MainProgramClass
{
public static void Main()
{
//Declare an instance of the delegate MyDelegate reference type

MyDelegate instDelegate;

//References or associates the parameter-less anonymous method 
//with the instance instDelegate of the delegate by assigning the 
//anonymous method to it as parameter using a single line 
//assignmnet

instDelegate = delegate() { Console.WriteLine("Hello"); };

//We can also reference or associate the anonymous method with 
//the instance instDelegate of the delegate by assigning the 
//anonymous method to it as parameter using the multiple lines 
//assignment

instDelegate = delegate()
{
Console.WriteLine("Hello");
};

//Invoke the anonymous method that displays a message on the screen

instDelegate();

Console.WriteLine("Press any key to exit ");
Console.ReadKey();
}
}
}

The Visual Basic.NET Program

Namespace ProgramNamespace

'Define a Delegate reference type that references or associates a 
'parameter-less anonymous method having no parameters and 
'does not return value

Delegate Sub MyDelegate()

Public Class MainProgramClass

Public Shared Sub Main()

'Declare an instance of the delegate MyDelegate reference type

Dim instDelegate As MyDelegate

'References or associates the parameter-less anonymous method 
'with the instance instDelegate of the delegate by assigning the 
'anonymous method to it as parameter using a single line 
'assignmnet

instDelegate = Sub() Console.WriteLine("Hello")

'We can also reference or associate the anonymous method with 
'the instance instDelegate of the delegate by assigning the 
'anonymous method to it as parameter using the multiple lines 
'assignment  

instDelegate = Sub() 
Console.WriteLine("Hello")
End Sub

'Invoke the anonymous method that displays a message on the screen

instDelegate()

Console.WriteLine("Press any key to exit ")
Console.ReadKey()
End Sub
End Class
End Namespace

The above program displays Hello on the screen using an anonymous method. In the program, we defined a delegate reference type MyDelegate that has no parameters and does not return value. In the main method of the program, we declared an instance instDelegate of the delegate reference type MyDelegate and it is instantiated by assigning an anonymous method that has no parameters and does not return any value. The instance instDelegate of MyDelegate reference type is then used and invoke the referenced anonymous method.

Program # 2

Write a program that adds two integer values using an anonymous method. The anonymous method takes two integer parameters and returns their sum to the calling point.

The C# Program

using System;

namespace ProgramNamespace
{
//Define a Delegate reference type that references or associates an 
//anonymous method having two integer parameters and return an 
//integer value

delegate int MyDelegate(int x, int y);

public class MainProgramClass
{
public static void Main()
{
//Declare an instance of the delegate MyDelegate reference type

MyDelegate instDelegate; 

//References or associates the parameterized anonymous method 
//with the instance instDelegate of the delegate by assigning the 
//anonymous method to it as parameter using a single line assignmnet 
  
instDelegate = delegate(int x, int y) {return x + y;};

//We can also reference or associate the anonymous method with 
//the instance insDelegate by assigning the anonymous method to it 
//as parameter using the multiple lines assignment

instDelegate = delegate(int x, int y) 
{
return x + y;
};

//Invoke the anonymous method and pass two integer values to it 
//and declare an integer variable to store the result of the 
//anonymous method

int result = instDelegate(2, 3);

//Display the result of the anonymous method
Console.WriteLine("The sum of two values = " + result);

Console.WriteLine("Press any key to exit ");
Console.ReadKey();
}
}
}

The Visual Basic.NET Program

Namespace ProgramNamespace

'Define a Delegate reference type that represents an anonymous 
'method having two integer parameters and integer return type 

Delegate Function MyDelegate(x As Integer, y As Integer) As Integer

Public Class MainProgramClass

Public Shared Sub Main()

'Declare an instance of the delegate MyDelegate reference type

Dim instDelegate As MyDelegate

'References or associates the parameterized anonymous method 
'with the instance instDelegate of the delegate by assigning the 
'anonymous method to it as parameter using a single line assignmnet

instDelegate = Function(x As Integer, y As Integer) x + y

'We can also reference or associate the anonymous method with 
'the instance insDelegate by assigning the anonymous method to it 
'as parameter using the multiple lines assignment

instDelegate = Function(x As Integer, y As Integer)
Return (x + y)
End Function

'Invoke the anonymous method and pass two integer values to it 
'and declare an integer variable to store the result of the anonymous method

Dim result As Integer = instDelegate(2, 3)

'Display the result of the anonymous method
Console.WriteLine("The sum of two values = " & result)

Console.WriteLine("Press any key to exit ")
Console.ReadKey()
End Sub
End Class
End Namespace

The Lambda Expression

A Lambda expression is a simplified form of an anonymous method that is used to write an anonymous method without its declaration in the form of an expression. It divides an anonymous method into two parts and makes an expression by placing an operator between them that is called Lambda operator. The declaration of an anonymous method always starts from a keyword delegate followed by a parameters list and its body. The parameters list of an anonymous method may contain zero or more parameters and each parameter requires its data type specification for example, if an anonymous method takes one or more parameters then we must specify the data type of each parameter. A Lambda Expression reduces a keyword delegate and the data type specifications of the parameters and it allows us to write an anonymous method without the using of the keyword delegate and the data type specifications of its parameters. The Lambda Expression allows us an option to declare all the input parameters of an anonymous method with their data type specifications or simply provide the names of the input parameters without their data type specifications. The compiler automatically manages the data types of the input parameters from the usage. A Lambda expression contains two parts separated by an operator that is called Lambda Operator. The Lambda operator is the combination of an equal operator and a greater than operator and it is represented as =>. The Lambda operator is placed between the two parts of the Lambda Expression in which the left side part of the Lambda Expression indicates the input parameters list of the anonymous method surrounded by small braces and the right side part of the Lambda Expression indicates the body of the anonymous method. The body of an anonymous method may contain a single or multiple statements. If body of an anonymous method contains a single statement, then usually it is written on the same line with the Lambda operator and if body of an anonymous method contains multiple statements, then it is surrounded by the curly braces { } just like an anonymous method.

To write an anonymous method using a Lambda Expression, it divides the anonymous method into two parts such as a parameters list and body of the anonymous method. The left side part of the Lambda Expression takes the input parameters of an anonymous method without its parameters data type specifications. It just takes the names of the input parameters and there is no need to specify their data types because the compiler automatically inferred the data types of the input parameters from the usage. The right side part of the Lambda Expression takes the body of the anonymous method. The Lambda Expression is introduced in C# 3.0. Following is the general syntax to declare a Lambda Expression:

([InputParametersList]) => {[BodyOfAnonymousMethod]};

The above syntax is a general syntax of a Lambda Expression that writes an anonymous method in two parts and makes an expression. The left side part of the Lambda Expression is ([ParametersList]) that indicates the number of input parameters of an anonymous method, the sign => indicates the Lambda operator, and the right side part of the Lambda Expression is [BodyOfAnonymousMethod] that indicates the body of an anonymous method. If body of an anonymous method contains more than one statement, then the body is surrounded by curly braces and the above syntax can be written as:

([InputParametersList]) => { [BodyOfAnonymousMethod] };
                           
                                              Or

                            ([ParametersList]) => 
                            {
                             BodyOfAnonymousMethod
                             };

The Benefits of using Lambda Expression

The Lambda Expression is a best choice to use it in the program to reduce the block of code and makes it easier and understandable. It reduces the complexity of an anonymous method and makes it simplify and shorter. A Lambda Expression reduces the delegate keyword from the declaration of an anonymous method and the data type specifications of its parameters. The main use of a Lambda Expression is to access the LINQ. If we want to access the LINQ in our program code, then the Lambda Expression is a best choice to access the LINQ.

Program # 3

Write a program that displays a message on the screen using a parameter-less anonymous method. The anonymous method uses a Lambda Expression.

The C# Program

using System;

namespace ProgramNamespace
{
//Define a delegate reference type that references or associates a 
//parameter-less anonymous method in the form of a Lambda 
//Expression having no parameters and does not return value

delegate void MyDelegate();

public class MainProgramClass
{
public static void Main()
{
//Declare an instance of the delegate MyDelegate reference type

MyDelegate instDelegate;

//References the Lambda Expression with the instance //instDelegate of the delegate 

instDelegate = () => { Console.WriteLine("Hello"); };

//Invoke the Lambda Expression using the instance of the delegate

instDelegate();

Console.WriteLine("Press any key to exit ");
Console.ReadKey();
}
}
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Adalat Khan
Software Developer (Senior) Abu Dhabi University
United Arab Emirates United Arab Emirates
Mr. Adalat Khan is a professional author of computer programming. He wrote many books on computer programming languages. His one book is published international by an Australian books publishing company Xlibris under the title "Learn Professional Programming Skill in C++ Programming Language". Mr. Adalat Khan has passed his Intermediate (F.Sc Pre Engineering) from Government Jehanzeb College Saidu Sharif Swat Pakistan and his Bachelor Degree “Bachelor of Computer Science (BCS)” from CECOS University of IT and Emerging Sciences Peshawar Pakistan and Master Degree “Master of Information Technology (MIT)” from GOMAL University Dera Ismail Khan Pakistan. Mr. Adalat Khan has worked in the field of C, C++ (Borland Turbo C++, ANSI standard of C++, Visual C++, Visual C++.NET) and other programming languages such as Visual Basic, Visual Basic.NET, C#, Visual C#, ASP.NET, SQL Server Database, Java, Java Script, VB Script, HTML, and DHTML.
Follow on   LinkedIn

Comments and Discussions

 
GeneralMy vote of 3 PinprofessionalAfzaal Ahmad Zeeshan25-Nov-14 9:17 
GeneralMy vote of 4 PinprofessionalSibeesh Venu5-Aug-14 21:54 
GeneralGood article Pinmemberwicklowwanderer30-Jul-14 9:44 
Questionit's good Pinmembermakegold28-Jul-14 5:58 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.150123.1 | Last Updated 28 Jul 2014
Article Copyright 2014 by Adalat Khan
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid