In C#, an anonymous function refers to a function lacking a specific name. This concept was first seen in C# 2.0 and proves beneficial for defining an inline unnamed method while accepting parameters, similar to conventional methods. To implement this, the delegate keyword is used, eliminating the need for a defined name and return type.
The <style> class defines a diagram container with a stylish design. It includes a background gradient, rounded corners, padding, and centered alignment for content. The diagram also features an icon with a size of 3rem and text styled in a color of #9ca3af and a font size of 1rem.
In C#, an anonymous function serves as a means to draft code directly without assigning it a specific name. It functions akin to a lambda expression, yet offers the flexibility to omit parameters when unnecessary. Consequently, we can assert that an anonymous method comprises solely of a body devoid of a designated name, with the option of parameters and return type.
Syntax:
It has the following syntax.
delegate(parameter_list)
{
// block of code
};
In this syntax,
- delegate: It defines an anonymous method without a name.
- parameter_list: It includes any input parameters.
- { }: It shows the method body of the program.
C# Anonymous Function Example:
Let's consider a scenario to demonstrate the anonymous function in C#.
Example
using System;
delegate void GreetDelegate(string name);
class Program
{
static void Main()
{
// Defining an anonymous method
GreetDelegate greet = delegate(string name)
{
Console.WriteLine("Hello, " + name + " ! ");
};
// Calling the anonymous method
greet("John");
}
}
Output:
Hello, John!
Explanation:
In this instance, we establish a delegate named GreetDelegate, which accepts a string parameter. Within the main function, we assign an unnamed function to this delegate utilizing the delegate keyword. Subsequently, it accepts an input name and displays a message for greeting.
Features of an Anonymous Function
There are several features of an anonymous function in C#. Some main features are as follows:
- In C#, an anonymous method is defined using the delegate keyword or => operator.
- It must be assigned to a delegate instance.
- It can access variables and functions from the outer (enclosing) scope.
- It can be passed as a parameter to methods that accept delegates.
- It can be utilized as an event handler.
Lambda Expression
In the C# programming language, a lambda function serves as an anonymous function capable of containing expressions and statements. Its primary purpose lies in generating delegates or expression tree types and is frequently employed as a parameter in method calls. Lambda expressions are widely used in LINQ queries to enhance code brevity and readability.
Syntax:
It has the following syntax.
(parameters) => expression_or_statement_block
In this particular format,
- arguments: These signify the values provided to the lambda expression, mirroring the function parameters.
- =>: Referred to as the lambda operator, this symbol serves as the divider between the parameters and the expression's body.
C# Lambda Expression Example
Let's consider a scenario to demonstrate the Lambda function in C#.
Example
using System;
class C# Tutorial
{
static void Main()
{
// Lambda expression to add two numbers
Func<int, int, int> add = (a, b) => a + b;
int result = add(10, 20);
Console.WriteLine("The sum of two numbers is " + result);
}
}
Output:
The sum of two numbers is 30
Explanation:
In this instance, we create a basic function that sums two whole numbers. The Func<int, int, int> delegate defines a function that accepts two arguments and produces an integer output. Subsequently, the lambda notation (a, b) => a + b indicates that the operation receives two values, a and b, and yields their total.
C# Example to Check Even or Odd program using Lambda Expression
Let's consider an illustration to verify if a number is even or odd utilizing a lambda function in C#.
Example
using System;
using System.Collections.Generic;
using System.Linq;
class C# Tutorial
{
static void Main()
{
List<int> n = new List<int> {5, 6, 7, 8, 9, 10,12, 12, 13, 14,15};
// Using a lambda expression
var en = n.Where(n => n % 2 == 0);
Console.WriteLine("The even numbers are ");
foreach (var num in en)
{
Console.WriteLine(num);
}
}
}
Output:
The even numbers are
6
8
10
12
12
14
Explanation:
In this instance, we showcase how a lambda function is applied to filter out even numbers from a given list. Initially, a list named n is established, comprising multiple integer values. Subsequently, the code employs LINQ's where clause (n => n % 2 == 0) to isolate the even integers. The outcomes are saved in the en variable, and each individual number is then displayed using a foreach iteration.
Anonymous Method with Func Delegate in C#
Let's consider a scenario to demonstrate the anonymous function using a Func Delegate in C#.
Example
using System;
class C# Tutorial
{
static void Main()
{
Func<int, string> check = delegate(int n)
{
if (n % 2 == 0)
return "Even";
else
return "Odd";
};
// Call the anonymous method
Console.WriteLine("The number 10 is " + check(10));
Console.WriteLine("The number 7 is " + check(7));
}
}
Output:
The number 10 is Even
The number 7 is Odd
Explanation:
In this instance, we declare the delegate keyword using a Func<int, string> delegate, designed to accept an integer input and produce a string output. Within the unnamed function, we implement an if-else statement to differentiate between even and odd numbers. When the input is divisible by 2, it identifies as even, otherwise, it categorizes as odd. Subsequently, we invoke the delegate by providing a number as an argument and display the outcome.
C# Example for Anonymous Method as an Event Handler
Let's consider a scenario to demonstrate event management utilizing an unnamed function in the C# programming language.
Example
using System;
public class Button
{
public event EventHandler Press;
public void Click()
{
if (Press != null)
Press(this, EventArgs.Empty);
}
}
class Program
{
static void Main()
{
Button bb = new Button();
// Assigning an anonymous method to the Press event
bb.Press += delegate (object sender, EventArgs e)
{
Console.WriteLine("Button was clicked! (Handled by anonymous method)");
};
// Simulate button click
bb.Click();
}
}
Output:
Button was clicked! (Handled by anonymous method)
Explanation:
In this instance, we illustrate the implementation of an anonymous function as an event handler. Initially, we establish a class named Button containing an event named Press and a function named Click that triggers the press event. Within the primary function, we instantiate a class button as bb, invoke the Click function, and display the result.
Difference between Anonymous method and Lambda Expression
There are numerous variances between the anonymous method and the lambda expression in the C# programming language. Some key distinctions include:
| Aspect | Anonymous Method | Lambda Expression |
|---|---|---|
| Introduced in | It was introduced in C# 2.0. It was the first way to write the inline and unnamed methods. | It was introduced in C# 3.0. It provides a more modern and expressive way to define inline functions. |
| Syntax | The syntax of an Anonymous method isdelegate (parameter) { }. | The syntax of a Lambda expression is(parameter) = > expression |
| Type Interface | It requires explicit parameter types to be declared. | It supports a type interface, which enables the compiler to automatically deduce the type of the parameter. |
| Usage | It is less commonly used than a Lambda Expression. | It is commonly utilized in LINQ queries, event handling, and functional programming. |
| Parameter | It can access ref and out parameters of the enclosing method. | It cannot access ref or out parameter from the enclosing method. |
Limitations of an Anonymous Method
There are several limitations of an anonymous method in C#. Some of them are as follows:
- It cannot have jump statements, including goto, break, or continue.
- It cannot access the ref or out parameter of the enclosing method.
- It cannot contain or access an unsafe code block.
- It cannot be utilized on the left-hand side of the is operator.
Conclusion
In summary, anonymous functions in C# provide a way to define functions inline without the need for explicit declaration. These functions contribute to code brevity, enhance readability, and prove beneficial when dealing with delegates and LINQ queries. Leveraging anonymous methods or lambda expressions enables the creation of more streamlined and adaptable code.
Anonymous Function FAQs
1) What is an anonymous function in C#?
An unnamed function, known as an anonymous function, lacks a specific identifier. This concept was first introduced in C# 2.0. It proves to be quite advantageous for users who wish to create a concise anonymous method and provide a parameter to it, mirroring the behavior of a standard method.
2) How can we define an anonymous function in C#?
In C#, a nameless function can be declared using the delegate keyword or through a lambda expression (=>).
Func<int, int> square = delegate (int x)
{
return x * x;
};
3) What are the main applications of a lambda function?
In C#, anonymous functions are primarily utilized for managing events, crafting LINQ queries, and generating concise, single-use functions where establishing a distinct named method would be superfluous. This approach aids in minimizing code complexity and simplifies maintenance in such scenarios.
4) What are the limitations of anonymous methods?
In C# programming, an anonymous function is restricted from using jump statements like goto, break, or continue. It is also prohibited from interacting with the ref or out parameters of the parent method and from including or accessing unsafe code blocks.
5) What is a Lambda Expression in C#?
A lambda expression serves as an unnamed function primarily employed for generating delegates. It enables the creation of local functions that can be passed as arguments and is particularly useful for constructing LINQ queries within C#.