Lambda Expressions and Anonymous Methods

Lambda Expressions and Anonymous Methods

Lambda expressions and anonymous class methods are advanced essential features in the C# programming language that allow C# programmers to define inline methods without requiring a formal class method declaration. Lambda expressions and anonymous C# methods allow programmers to pass program source code as arguments, which is useful for program behavior scenarios such as LINQ queries, event handling, and delegation.

Lambda Expressions and Anonymous Methods

Lambda Expression in C#

A simple concept for representing anonymous class methods in a C# program by providing a special syntax for applying a user-defined lambda expression. Lambda expressions are often used with delegate methods, especially when passing data from a class to a LINQ query and in other program situations where a class method is passed as a variable data type or parameter.

Syntax of a lambda expression in C#.

(parameters) => expression_or_statement_block

Element of a lambda expression in C#.

  • Parameter – The input parameters (like method parameters) of a lambda expression defined in a C# program are defined in the lambda class program.
  • Arrow (=>) – Here, the class defines the parameters separately from the body of the lambda expression in a C# program.
  • Expression or statement block – This is the declaration body of a lambda expression, which can be either a single expression or a statement block in the program.

Example of a lambda expression in C#.

So, let’s better understand what a lambda expression is and how it works in a C# program by declaring or defining a lambda with one parameter.

Func<int, int, int> Total = (p, q) => p + q;

Console.WriteLine(Total(1, 2 )); // Result is – 3

Explanation of lambda expression.

  • In this example, Function<int, int, int> is a user-defined delegate method type that accepts two integer values ​​p and q as input in the current program and returns an integer value as output.
  • In this example, a user-defined lambda expression, Total = (p, q) => p + q;, represents a simple integer total operation.

Lambda expression without parameters in C#.

Here, we create a lambda expression that returns a text console message indicating the lambda expression action performed.

Info = () => Console.WriteLine(“Welcome to, Vcanhelpsu”);

Info(); // Result is – Welcome to, Vcanhelpsu

  • Here, the action is a delegate method that returns no value (i.e., void) to the current lambda expression.
  • The lambda expression defined here, Info = () => Console.WriteLine(“Welcome to, Vcanhelpsu”); , does not take any variable or parameter values ​​as input from the user, and prints a message to a user-defined console screen.

Lambda expression with multiple parameters and a statement block in C#.

Func<int, int, int> product = (p, q) =>

{

int output = p * q;

return output ;

};

Console.WriteLine(product(9, 3)); // Result is – 27

Multiple parameters and a statement block example.

Here, the program uses a block of source code inside a lambda expression (with { }) to multiply the above lambda expression and display its output result.

A group of lambda expressions example in C#.

using System;

class Program

{

static void Main()

{

// Here we define a Lambda expression p, and q as lambda expressions for adding two numbers

Func<int, int, int> Total = (p, q) => p + q;

Console.WriteLine(Total(1, 2)); // Result is – 3

// Here we define a Lambda expression with no variable parameters value

Action Info = () => Console.WriteLine(“Welcome to, Vcanhelpsu”);

Info(); // Result is – Welcome to Vcanhelpsu

// Here we define a Lambda expression for multiplication of two integers

Func<int, int, int> product = (p, q) =>

{

int output = p * q;

return output;

};

Console.WriteLine(product(9, 3)); // Result is – 27

}

}

Using Lambda Expressions in C# LINQ.

In C# programming, lambda expressions are mostly used in LINQ queries to filter specific program data information, modify data, or collect group data.

using System;

using System.Collections.Generic;

using System.Linq;

class Program

{

static void Main()

{

List<int> integers = new List<int> { 8, 1, 22, 3, 100, 7, 122, 9 };

var oddintegers = integers.Where(n => n % 2 != 0).ToList();

foreach (var intgr in oddintegers)

{

Console.WriteLine(intgr); // Result is – 1 3 7 9

}

}

}

Explain Lambda Expressions.

  • In this program, integers.Where(n => n % 2 != 0). is a user-defined LINQ method that uses lambda expressions to filter the given list data and select and display only the odd numbers.

Anonymous Method in C#.

An anonymous method in C# programming is a user-defined class program method that does not have a name defined in the program. However, it can be defined inline in the program if needed, and can be assigned to a delegate declared in a class. An anonymous method in C# programming is specifically used when C# users want to pass program source code as a direct class argument without having to declare a new class method separately in the program.

The syntax of an anonymous method in C# programming.

delegateType delegateName = delegate(parameters)

{

// Here we can user define a class method body

};

Element of anonymous method in C#.

  • delegateType – This is a type method of the delegate in the current program expression, which will be assigned as an anonymous method in the active program.
  • delegate(parameters) – Here, after the keyword delegate, comes the user-defined variable parameter list and the class method body for the method.

Example of an anonymous method in C#.

using System;

delegate void DisplayDelegate(string company_name);

class Program

{

static void Main()

{

// Here we define an anonymous method assignment to the delegate

DisplayDelegate info = delegate(string company_name)

{

Console.WriteLine(“Hi, ” + company_name);

};

info(“Vcanhelpsu Edtech”); // Result is – Hi, Vcanhelpsu Edtech

}

}

Explanation of an anonymous method in C#.

  • Here in this program, an anonymous class method delegate assigns delegate(string company_name) and { Console.WriteLine(“Hi, ” + company_name); } to the DisplayDelegate delegate.

Lambda Expressions vs. Anonymous Methods in C#.

  • As in C# programming, both lambda expressions and anonymous class methods help C# users declare or define inline methods. However, both lambda expressions and anonymous class methods have their own unique functions and features.

Lambda Expressions vs. Anonymous Methods Syntax.

  • Lambda expressions declared in C# programs are smaller and more concise, and are defined using the arrow => operator. Similarly, anonymous methods declared in C# programs are defined or declared using the delegate keyword.

Lambda Expressions vs. Anonymous Methods Return Data Type.

  • Creating a lambda expression in a C# program can be defined as an expression, a function class body, or a statement block with a return data type value.
  • Similarly, anonymous class methods always require a return statement if the current program has the possibility of returning a value.

Capturing Variables in Lambda Expressions vs. Anonymous Methods.

  • In C# programming, both lambda expressions and anonymous class methods can capture parameter variable values ​​from the enclosing scope. However, lambda expressions offer greater flexibility and reliability in capturing local variables or parameters.

Lambda Expressions vs. Anonymous Methods Type Inference.

In C# programming, lambda expressions can take advantage of type inference, which means the C# compiler can automatically infer anonymous delegate types in the current program. In contrast, the frequency of data type inference in anonymous class methods is not the same.

Example comparison of lambda expressions and anonymous methods in C#.

Using System;

class program

{

delegate void PreviewDelegate(string info);

static void Main()

{

// here we define an Anonymous class method

PreviewDelegate text1 = delegate (string info)

{

Console.WriteLine(“\n this is an Anonymous method. ” + info);

};

text1(“\n Here We successfully test anonymous method\t”);

// here we use Lambda expression to display console screen message

PreviewDelegate print2 = (info) => Console.WriteLine(“\n this is a Lambda expression. ” + info);

print2(“\nHere We successfully test lambda expression\t”);

}

}

Explanation of comparison of lambda expressions and anonymous methods.

  • In this program, the anonymous class method is declared using the delegate keyword, and the lambda expression is defined using the => syntax.
  • Here, both class methods provide the same result as program output. However, the syntax and declaration of the lambda expression are shorter.

Using Lambda Expressions and Anonymous Methods with Events.

Lambda expressions and anonymous methods are often used for event handling in C# programs. They provide a clear and compact way to create event handlers without explicitly defining class methods in the program.

Example of using lambdas for event handling in a C# program.

Using System;

class TestButton

{

public event EventHandler Click;

public void OnClick()

{

Click?.Invoke(this, EventArgs.Empty);

}

}

class program

{

static void Main()

{

TestButton testbutton = new TestButton();

// here we are using the lambda expression for button event handling

testbutton.Click += (push, p) =>

{

Console.WriteLine(“Now Button is pressed”);

};

testbutton.OnClick(); // Result is – Now Button is pressed

}

}

Explanation of using lambdas for event handling.

  • Here in this program the lambda expression (push, p) =>{ Console.WriteLine(“Now Button is pressed”); }; is used to handle and manage the Click button event.

C# Programming Lambda Expressions and Anonymous Methods Summary.

Lambda Expressions Summary.

  • Lambda expressions provide a simple way to create inline functions.
  • They are commonly used with LINQ, delegates, and events in C# programming.
  • The syntax of a lambda expression is: (parameters) => expression_or_statement_block.
  • Lambda expressions can return a value directly to the program, or use a block of program source code.

Anonymous Method Summary.

  • They help you define anonymous class methods inline in C# programming, and assign them to delegates used in the class.
  • Anonymous Syntax in C# Programming: delegate(parameters) { // method body }.
  • It is used in class method scenarios where the class method definition is not required throughout the program.

Difference between Lambda Expressions and Anonymous Methods.

  • Declared lambda expressions in C# programs are generally smaller, more flexible, and reliable than anonymous methods.
  • Lambda expressions in C# programs fully support type inference, while declared anonymous methods in classes do not.

Using Lambda Expressions and Anonymous Methods.

  • Both lambda expressions and anonymous class method concepts are used extensively in C# programs for program event handling, parameter variable lists, data LINQ queries, and passing behavior as arguments.

Leave a Reply