Dotnet Notes Upto Lambda Expression
Dotnet Notes Upto Lambda Expression
Syntax:
[modifier] delegate [return_type] [delegate_name] ([parameter_list]);
• modifier: It is the required modifier which defines the access of delegate and it is
optional to use.
• delegate: It is the keyword which is used to define the delegate.
• return type: It is the type of value returned by the methods which the delegate will be
going to call. It can be void. A method must have the same return type as the delegate.
• delegate_name: It is the user-defined name or identifier for the delegate.
• parameter_list: This contains the parameters which are required by the method when
called through the delegate.
Example:
public delegate int DelegateTest(int x, int y, int z);
Note: A delegate will call only a method which agrees with its signature and return type. A
method can be a static method associated with a class or can be an instance method
associated with an object, it doesn’t matter.
For example
[delegate_name] [instance_name] = new [delegate_name] (method_name);
Output:
Result is : 25
Example of delegate in multiple class
using System;
public delegate void MyDelegate(int a,int b);
class A
{
public void Add(int a,int b){
int sum=a+b;
Console.WriteLine("Sum is: {0}",sum);
}
}
class Program{
static void Main(){
A obj=new A();
MyDelegate del=new MyDelegate(obj.Add);
del(20,30);
}
}
Output:
Sum is: 50
Multicast Delegates
All delegate instances have multicast capability. This means that a delegate instance can reference
not just a single target method, but also a list of target methods.
It has zero or more input parameters and one out parameter. The last parameter is
considered as an out parameter.
The Func delegate that takes one input parameter and one out parameter is defined in the
System namespace, as shown below:
Output:
20
Action Delegate
Action is a delegate type defined in the System namespace. An Action type delegate is the
same as Func delegate except that the Action delegate doesn't return a value.
In other words, an Action delegate can be used with a method that has a void return type.
An Action delegate can take up to 16 input parameters of different types.
Action<int, string, double, bool, char, DateTime, float, long, short, decimal, uint, ulong, sbyte,
byte, object, Guid> action = (i, s, d, b, c, dt, f, l, sh, de, u, ul, sb, by, o, g) => {
Console.WriteLine($"Int: {i}, String: {s}, Double: {d}, Bool: {b}, Char: {c}, DateTime: {dt},
Float: {f}, Long: {l}, Short: {sh}, Decimal: {de}, UInt: {u}, ULong: {ul}, SByte: {sb}, Byte:
{by}, Object: {o}, Guid: {g}"); }; action(1, "example", 1.23, true, 'A', DateTime.Now, 1.23f,
123456789L, (short)123, 1.23m, 123U, 1234567890123456789UL, (sbyte)1, (byte)1, new
object(), Guid.NewGuid());For example, the following delegate prints an int value.
public delegate void Print(int a);
static void ConsolePrint(int a)
{
Console.WriteLine(a);
}
static void Main(string[] args)
{
Print prnt = ConsolePrint;
prnt(10);
}
Output
10
You can use an Action delegate instead of defining the above Print delegate, for example:
static void ConsolePrint(int a)
{
Console.WriteLine(a);
}
static void Main(string[] args)
{
Action<int> printActionDel = ConsolePrint;
printActionDel(10);
}
Output:
10
Anonymous Method in C#
An anonymous method is a method which doesn’t contain any name which is introduced in
C# 2.0. It is useful when the user wants to create an inline method and also wants to pass
parameter in the anonymous method like other methods.
An Anonymous method is defined using the delegate keyword and the user can assign this
method to a variable of the delegate type.
delegate(parameter_list){
// Code..
};
Following are the features of anonymous method:
1. Anonymous method can be defined using the delegate keyword
2. Anonymous method must be assigned to a delegate.
3. Anonymous method can access outer variables or functions.
4. Anonymous method can be passed as a parameter.
5. Anonymous method can be used as event handlers.
Events
Events in C# provide a way for a class or object to send notifications to other classes or objects
when something of interest occurs. They are based on the publisher-subscriber model, where the
class that sends the event is called the publisher and the class that receives the event is called
the subscriber.
Key Concepts of Events in C#
1. Event Delegates: An event is associated with a delegate that defines the signature for the
method that will handle the event. The delegate is used to specify the type of method that
can respond to the event.
2. Defining Events: Events are defined in a class using the event keyword, based on a
delegate type.
3. Raising Events: To notify subscribers when an event has occurred, the publisher calls the
event.
4. Subscribing to Events: Subscribers can register their event handler methods with an
event, which gets invoked when the event is raised.
5. Unsubscribing from Events: Subscribers can also unregister their handlers when they
are no longer interested in the event.
Example of Using Events in C#
Here’s a simple example to illustrate how events work in C#.
using System;
// Step 1: Define a delegate
public delegate void TemperatureChangedEventHandler(object sender,
TemperatureChangedEventArgs e);
Lambda Expressions
In C#, a lambda expression is a concise way to represent an anonymous function that can contain
expressions and statements. Lambda expressions are particularly useful for creating delegates or
standalone methods. They are often used with LINQ queries and other operations that work with
collections.
The ‘=>’ is the lambda operator which is used in all lambda expressions. The Lambda
expression is divided into two parts; the left side is the input and the right is the expression.
The Lambda Expressions can be of two types:
Expression Lambda: Expression Lambda in C# is a concise way to represent an anonymous
method. It can take parameters and execute a single expression, returning the result of that
expression. Lambda expressions are often used in LINQ queries and when working with
delegates and events. Consists of the input and the expression.
Syntax:
(parameters) => expression
input => expression;
Statement Lambda: Statement Lambda is also an anonymous function, but it allows for more
complex operations that may include multiple statements. Instead of a single expression, a
lambda statement can contain a block of code enclosed in braces. Consists of the input and a set
of statements to be executed. It
can be used along with delegates.
Syntax:
(parameters) => { statements; }
input => { statements };
Key Differences
• Return Type: Lambda expressions implicitly return the result of their single expression,
while lambda statements do not automatically return anything unless an explicit return
statement is used.
• Complexity: Lambda expressions are generally used for simple functions, whereas
lambda statements can handle more complex logic with multiple statements.
Output:
Sum=30