0% found this document useful (0 votes)
7 views20 pages

Dotnet Notes Upto Lambda Expression

This document covers advanced C# concepts including delegates, events, lambda expressions, exception handling, LINQ, database interaction, and web applications using ASP.NET. It explains the definition, declaration, instantiation, and invocation of delegates, as well as multicast delegates and built-in delegate types like Func and Action. Additionally, it discusses anonymous methods, event handling, and the use of lambda expressions for concise function representation.

Uploaded by

pravesh koirala
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views20 pages

Dotnet Notes Upto Lambda Expression

This document covers advanced C# concepts including delegates, events, lambda expressions, exception handling, LINQ, database interaction, and web applications using ASP.NET. It explains the definition, declaration, instantiation, and invocation of delegates, as well as multicast delegates and built-in delegate types like Func and Action. Additionally, it discusses anonymous methods, event handling, and the use of lambda expressions for concise function representation.

Uploaded by

pravesh koirala
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

Unit - 4 Advanced C#

Delegates; Events; Lambda Expressions; Exception Handling; Introduction to LINQ; Working


with Databases; Web Applications using ASP.NET
Delegates
A delegate is an object that knows how to call a method. A delegate type defines the kind
of method that delegate instances can call. Specifically, it defines the method’s return type
and its parameter types.
Delegates are especially used for implementing events and the call-back methods. All
delegates are implicitly derived from the System. Delegate class. It provides a way which tells
which method is to be called when an event is triggered.
For example, if you click an Button on a form (Windows Form application), the program
would call a specific method.
In simple words, it is a type that represents references to methods with a particular parameter
list and return type and then calls the method in a program for execution when it is needed.
Declaring Delegates
Delegate type can be declared using the delegate keyword. Once a delegate is declared,
delegate instance will refer and call those methods whose return type and parameter-list
matches with the delegate declaration.

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.

Instantiation & Invocation of Delegates


Once a delegate type is declared, a delegate object must be created with the new keyword
and be associated with a particular method. When creating a delegate, the argument passed
to the new expression is written similar to a method call, but without the arguments to the
method.

For example
[delegate_name] [instance_name] = new [delegate_name] (method_name);

DelegateTest obj = new DelegateTest (MyMethod);


// here,
// " DelegateTest" is delegate name.
// " obj" is instance_name
// " MyMethod" is the calling method.

Example of simple delegate is shown below:


using System;
public delegate int MyDelegate(int x);
class DelegateTest
{
static int MyMethod(int x)
{
return x * x;
}
static void Main(string[] agrs)
{
MyDelegate del = new MyDelegate(MyMethod);
int res = del(5); //25
Console.WriteLine("Result is : "+res);
Console.ReadKey();
}
}

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.

The + and += operators combine delegate instances.


For example:
SomeDelegate d = SomeMethod1;
d += SomeMethod2;
The last line is functionally the same as:
d = d + SomeMethod2;
Invoking d will now call both SomeMethod1 and SomeMethod2. Delegates are invoked in
the order they are added.
The - and -= operators remove the right delegate operand from the left delegate operand.
For example:
d -= SomeMethod1;
Invoking d will now cause only SomeMethod2 to be invoked.
Calling + or += on a delegate variable with a null value works, and it is equivalent to
assigning the variable to a new value:
SomeDelegate d = null;
d += SomeMethod1; // Equivalent (when d is null) to d =
SomeMethod1;
Similarly, calling -= on a delegate variable with a single target is equivalent to assigning null
to that variable.

Example of Delegate Multicasting


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);
}
public void Diff(int a,int b){
int diff=a-b;
Console.WriteLine("Difference is: {0}",diff);
}
public void Multiply(int a,int b){
int mul=a*b;
Console.WriteLine("Product is: {0}",mul);
}
}
class Program{
static void Main(){
A obj=new A();
MyDelegate del=new MyDelegate(obj.Add);
//Multicasting
del+=obj.Diff;
del+=obj.Multiply;
del-=obj.Add;
del(20,30);
}
}
Output:
Difference is: -10
Product is: 600
Func Delegate
C# includes built-in generic delegate types Func and Action, so that you don't need to define
custom delegates manually in most cases. Func is a generic delegate included in the System
namespace.

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:

public delegate TResult Func<in T, out TResult>(T arg);


The following Func delegate takes two input parameters of int type and returns a value of
int type:
Func<int, int, int> sum;
Example is shown below:
class Program
{
static int Sum(int x, int y)
{
return x + y;
}
static void Main(string[] args)
{
Func<int,int, int> add = Sum;
int result = add(10, 10);
Console.WriteLine(result);
}
}

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.

Example of Anonymous Method


using System;
class Program{
//defining delegate
public delegate void MyDel(int a,int b);
static void Main(){
//Example of anonymous method
MyDel del=delegate(int a,int b){
int sum=a+b;
Console.WriteLine("Sum={0}",sum);
};
del(20,30);
}
}
Output:
Sum=50

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);

// Step 2: Define an EventArgs class for passing additional information


public class TemperatureChangedEventArgs : EventArgs
{
public double NewTemperature { get; set; }

public TemperatureChangedEventArgs(double newTemperature)


{
NewTemperature = newTemperature;
}
}

// Step 3: Create a publisher class


public class TemperatureSensor
{
private double temperature;

// Step 4: Declare the event using the delegate


public event TemperatureChangedEventHandler TemperatureChanged;

public double Temperature


{
get { return temperature; }
set
{
// Raise event if temperature changes
if (temperature != value)
{
temperature = value;
OnTemperatureChanged(new TemperatureChangedEventArgs(temperature));
}
}
}

// Step 5: Protected virtual method to raise the event


protected virtual void OnTemperatureChanged(TemperatureChangedEventArgs e)
{
TemperatureChanged?.Invoke(this, e);
}
}

// Step 6: Create a subscriber class


public class TemperatureDisplay
{
public void Subscribe(TemperatureSensor sensor)
{
sensor.TemperatureChanged += OnTemperatureChanged;
}

private void OnTemperatureChanged(object sender, TemperatureChangedEventArgs e)


{
Console.WriteLine($"Temperature changed to: {e.NewTemperature}°C");
}
}

// Step 7: Demonstrate the event


class Program
{
static void Main()
{
TemperatureSensor sensor = new TemperatureSensor();
TemperatureDisplay display = new TemperatureDisplay();

// Subscribe to the event


display.Subscribe(sensor);

// Simulate temperature changes


sensor.Temperature = 25.0;
sensor.Temperature = 30.5;
sensor.Temperature = 20.3;
}
}

Explanation of the Example:


• Delegate: TemperatureChangedEventHandler is defined as a delegate type that has a
method signature which takes an object and TemperatureChangedEventArgs.
• EventArgs Class: TemperatureChangedEventArgs is a custom class inheriting
from EventArgs, providing additional data (new temperature) to the event handler.
• Publisher (TemperatureSensor): This class has an event called TemperatureChanged,
which raises whenever the temperature changes. The method OnTemperatureChanged is
responsible for raising the event.
• Subscriber (TemperatureDisplay): This class subscribes to
the TemperatureChanged event and defines how to handle the event when it occurs.
• Demonstration: In the Main method, we create instances of both the sensor and display,
subscribe to the event, and simulate temperature changes to demonstrate event
notification.

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.

Example of Expression Lambda


using System;
class Program {
//Expression lambda
public int Test(int a)=>a+10;
public int Add(int a,int b)=>a+b;
static void Main(){
Program obj=new Program();
int res;
res=obj.Test(5); //returns 15
Console.WriteLine("Result={0}",res);
res=obj.Add(10,20); //returns 30
Console.WriteLine("Result={0}",res);
}
}
Output:
Result=15
Result=30

Example of Statement Lambda


using System;
class Program{
//defining delegate
public delegate void MyDel(int a,int b);
static void Main(){
//statement lambda
MyDel del=(a,b)=>{
int add=a+b;
Console.WriteLine("Sum={0}",add);
};
del(10,20);
}
}

Output:
Sum=30

You might also like