Month End Sale: Get Extra 10% OFF on Job-oriented Training! Offer Ending in
D
H
M
S
Get Now

C#: Anonymous Method & Lambda Expression

Level : Advanced
Mentor: Shailendra Chauhan
Duration : 00:02:00

Anonymous Method:

An anonymous method is a C# feature that allows you to define inline, unnamed methods using the delegate keyword. They are often used for ad-hoc event handling and delegate assignments.

Lambda Expression:

A lambda expression is a concise way to define anonymous methods in C#. It provides a more readable and compact syntax for defining delegates and inline functions.

Action Lambda:

An action lambda is a lambda expression that represents a method taking no parameters and having no return value (void). It's typically used for performing actions or side effects.

Example:

Action greet = () => Console.WriteLine("Hello!");
greet(); // Invoke the action

Func Lambda:

A func lambda is a lambda expression that represents a method taking one or more parameters and returning a value. It's suitable for defining functions and calculations.

Example:

Func<int, int, int> add = (a, b) => a + b;
int result = add(5, 3); // Invoke the function
Console.WriteLine("Result: " + result);

Predicate Lambda:

A predicate lambda is a specialized form of Func that takes one or more parameters and returns a Boolean value. It's commonly used for filtering and testing conditions.

Example:

Predicate<int> isEven = x => x % 2 == 0;
bool even = isEven(6); // Check if a number is even
Console.WriteLine("Is Even: " + even);

Expression Tree:

An expression tree in C# represents code as a data structure. It allows you to manipulate and analyze code at a higher level of abstraction. Expression trees are often used in LINQ and dynamic query scenarios.

Example:

// Create an expression tree for an addition operation
Expression<Func<int, int, int>> addExpression = (a, b) => a + b;
// Compile and execute the expression tree
var addFunc = addExpression.Compile();
int result = addFunc(5, 3);
Console.WriteLine("Result: " + result);
Self-paced Membership
  • 22+ Video Courses
  • 800+ Hands-On Labs
  • 400+ Quick Notes
  • 55+ Skill Tests
  • 45+ Interview Q&A Courses
  • 10+ Real-world Projects
  • Career Coaching Sessions
  • Email Support
Upto 60% OFF
Know More
Still have some questions? Let's discuss.
CONTACT US
Accept cookies & close this