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
{
delegate void MyDelegate();
public class MainProgramClass
{
public static void Main()
{
MyDelegate instDelegate;
instDelegate = delegate() { Console.WriteLine("Hello"); };
instDelegate = delegate()
{
Console.WriteLine("Hello");
};
instDelegate();
Console.WriteLine("Press any key to exit ");
Console.ReadKey();
}
}
}
The Visual Basic.NET Program
Namespace ProgramNamespace
Delegate Sub MyDelegate()
Public Class MainProgramClass
Public Shared Sub Main()
Dim instDelegate As MyDelegate
instDelegate = Sub() Console.WriteLine("Hello")
instDelegate = Sub()
Console.WriteLine("Hello")
End Sub
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
{
delegate int MyDelegate(int x, int y);
public class MainProgramClass
{
public static void Main()
{
MyDelegate instDelegate;
instDelegate = delegate(int x, int y) {return x + y;};
instDelegate = delegate(int x, int y)
{
return x + y;
};
int result = instDelegate(2, 3);
Console.WriteLine("The sum of two values = " + result);
Console.WriteLine("Press any key to exit ");
Console.ReadKey();
}
}
}
The Visual Basic.NET Program
Namespace ProgramNamespace
Delegate Function MyDelegate(x As Integer, y As Integer) As Integer
Public Class MainProgramClass
Public Shared Sub Main()
Dim instDelegate As MyDelegate
instDelegate = Function(x As Integer, y As Integer) x + y
instDelegate = Function(x As Integer, y As Integer)
Return (x + y)
End Function
Dim result As Integer = instDelegate(2, 3)
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
{
delegate void MyDelegate();
public class MainProgramClass
{
public static void Main()
{
MyDelegate instDelegate;
instDelegate = () => { Console.WriteLine("Hello"); };
instDelegate();
Console.WriteLine("Press any key to exit ");
Console.ReadKey();
}
}
}