0% found this document useful (0 votes)
3 views

delegates n events

The document provides an overview of delegates, events, and exception handling in C#. It explains how delegates allow passing methods as parameters, how events are triggered by user actions and handled through delegates, and the structured approach to exception handling using try, catch, finally, and throw keywords. Key concepts such as multicast delegates and the publisher-subscriber model for events are also discussed, along with examples and exception classes in C#.

Uploaded by

Priyanka Naik
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

delegates n events

The document provides an overview of delegates, events, and exception handling in C#. It explains how delegates allow passing methods as parameters, how events are triggered by user actions and handled through delegates, and the structured approach to exception handling using try, catch, finally, and throw keywords. Key concepts such as multicast delegates and the publisher-subscriber model for events are also discussed, along with examples and exception classes in C#.

Uploaded by

Priyanka Naik
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 30

Delegates, Events,

Exception Handling
C# - Delegates
What if we want to pass a function as a parameter?
How does C# handles the callback functions or event
handler?
The answer is - delegate.
The delegate is a reference type data type that defines
the method signature.
You can define variables of delegate, just like other
data type, that can refer to any method with the same
signature as the delegate.
There are three steps involved while working with
delegates:
Declare a delegate
Set a target method
Invoke a delegate
A delegate can be declared using
the delegate keyword.
Delegate Syntax
[access modifier] delegate [return type]
[delegate name]([parameters])
Example: Declare a Delegate
public delegate void MyDelegate(string msg);
we have declared a delegate MyDelegate with a
void return type and a string parameter.
 A delegate can be declared outside of the class
or inside the class.
 Practically, it should be declared out of the class.
After declaring a delegate, we need to set the
target method or a lambda expression.
We can do it by creating an object of the delegate
using the new keyword and passing a method
whose signature matches the delegate signature.
Example: Set Delegate Target
public delegate void MyDelegate(string msg); // declare a
delegate
// set target method
MyDelegate del = new MyDelegate(MethodA);
// or
MyDelegate del = MethodA;
// or set lambda expression
MyDelegate del = (string msg) => Console.WriteLine(msg);
// target method
static void MethodA(string message)
{
Console.WriteLine(message);
}
 You can set the target method by assigning a method
directly without creating an object of delegate e.g.,
MyDelegate del = MethodA.
After setting a target method, a delegate can
be invoked using the Invoke() method or using
the () operator.
Example: Invoke a Delegate
del.Invoke("Hello World!");
// or
del("Hello World!");
Example: Delegate
public delegate void MyDelegate(string msg); //declaring a
delegate
class Program
{
static void Main(string[] args)
{
MyDelegate del = ClassA.MethodA;
del("Hello World");

del = ClassB.MethodB;
del("Hello World");

del = (string msg) => Console.WriteLine("Called lambda


expression: " + msg);
del("Hello World");
}
}
class ClassA
{
static void MethodA(string message)
{
Console.WriteLine("Called ClassA.MethodA() with
parameter: " + message);
}
}

class ClassB
{
static void MethodB(string message)
{
Console.WriteLine("Called ClassB.MethodB() with
parameter: " + message);
}
}
Multicast Delegate
 The delegate can point to multiple methods. A delegate
that points multiple methods is called a multicast
delegate.
 The "+" or "+=" operator adds a function to the invocation
list, and the "-" and "-=" operator removes it.
Example: Multicast Delegate
public delegate void MyDelegate(string msg); //declaring a
delegate
class Program
{
static void Main(string[] args)
{
MyDelegate del1 = ClassA.MethodA;
MyDelegate del2 = ClassB.MethodB;
MyDelegate del = del1 + del2; // combines del1 + del2
del("Hello World");
MyDelegate del3 = (string msg) =>
del += del3; // combines del1 + del2 + del3
del("Hello World");
del = del - del2; // removes del2
del("Hello World");
del -= del1 // removes del1
del("Hello World");
}
}
class ClassA
{
static void MethodA(string message)
{
Console.WriteLine("Called ClassA.MethodA() with parameter: " +
message);
}
}
class ClassB
{
static void MethodB(string message)
{
Console.WriteLine("Called ClassB.MethodB() with parameter: " +
message);
}
}
If a delegate returns a value, then the
last assigned target method's value
will be return when a multicast
delegate called.
Example: Multicast Delegate Returning a
Value
public delegate int MyDelegate(); //declaring a delegate
class Program
{
static void Main(string[] args)
{
MyDelegate del1 = ClassA.MethodA;
MyDelegate del2 = ClassB.MethodB;

MyDelegate del = del1 + del2;


Console.WriteLine(del());// returns 200
}
class ClassA
{
static int MethodA()
{
return 100;
}
}
class ClassB
{
static int MethodB()
{
return 200;
}
}
Points to Remember :
Delegate is the reference type data type that defines
the signature.
Delegate type variable can refer to any method with
the same signature as the delegate.
Syntax: [access modifier] delegate [return type]
[delegate name]([parameters])
A target method's signature must match with
delegate signature.
Delegates can be invoke like a normal function or
Invoke() method.
Multiple methods can be assigned to the delegate
using "+" or "+=" operator and removed using "-" or
"-=" operator. It is called multicast delegate.
If a multicast delegate returns a value then it returns
the value from the last assigned target method.
Delegate is used to declare an event and anonymous
methods in C#.
WHAT IS EVENTS?
Events are nothing just a user action. For example
When you click with the mouse – It is mouse click events.
When you press any key in keyboard – It is KeyPress events
When you refresh your webpage – It is page load events
When you move mouse cursor – It is mouse hover events
etc.
So when you take any action like a key press, mouse
movements, clicks etc an event raised. Let me clear
more about it. For example, you filled an online form
and click on submit button.

In the background button_click() event raised.


This event calls and execute an associated function
Submit_Click().
This function processes your request and submits page
information to database.
HOW EVENTS WORK WITH DELEGATES?
Delegates are used to reference a method. An
Event is associated with Event Handler using
Delegates.
When an Event raise, it sends a signal to delegates
and delegates executes the right function.
WHAT IS PUBLISHER-SUBSCRIBER MODEL?
There are two parts in any event handling program.
A publisher is an object that contains the
definition of the event and the delegate. The event-
delegate association is also defined in this object. A
publisher class object invokes the event and it is
notified to other objects.
A subscriber is an object that accepts the event
and provides an event handler. The delegate in the
publisher class invokes the method (event handler)
of the subscriber class.
IMPORTANT FACT ABOUT
EVENTS
An Event is created using event
keyword.
An Event has no return type and it
is always void.
All events are based on delegates.
All the published events must
have a listening object.
All Events should be defined
starting with “On” keyword.
Let's understand all these theory using
Programming Example
Before seeing the programming examples you
must know the sequential steps to manipulate
events.

Step 1: Define a Delegate


Step 2: Define an Event with same name of
Delegates.
Step 3: Define an Event Handler that respond
when event raised.
Step 4: You must have method ready for
delegates.
using System; //Event gets binded with
delegates
namespace event
a.ev_OddNumber
{ += new
//This is AddTwoNumbers.dg_Od
Subscriber Class dNumber(EventMessage
class Program );
a.Add();
{
Console.Read();
static void }
Main(string[] args) //Delegates calls this
method when event
AddTwoNumbers a raised.
= new static void
AddTwoNumbers(); EventMessage()

{ { Console.WriteLine("
class AddTwoNumbers
{
public delegate void dg_OddNumber(); //Declared Delegate
public event dg_OddNumber ev_OddNumber; //Declared
Events

public void Add()


{
int result;
result = 5 + 4;
Console.WriteLine(result.ToString());
//Check if result is odd number then raise event
if((result % 2 != 0) && (ev_OddNumber != null))
{
ev_OddNumber(); //Raised Event
}
}
}
}
There are some marking on the code. We will go through the
marking and understand the process.
1. Delegate Created
public delegate void dg_OddNumber();
2. Event Created
public event dg_OddNumber ev_OddNumber;
3. ev_OddNumber() event gets executed if the odd number is
found.
4. In the AddTwoNumbers class there is a function void Add() that
adds two numbers. If the sum of the number is Odd it raised an
ev_OddNumber event. In the main function this ev_OddNumber
event handler calls the delegates
1. a.ev_OddNumber += new
AddTwoNumbers.dg_OddNumber(EventMessage);
5. Then finally delegate executes the function.
static void EventMessage()
{
Console.WriteLine("********Event Executed : This is Odd
Number**********");
}
C# - Exception Handling
An exception is a problem that arises during
the execution of a program.
A C# exception is a response to an
exceptional circumstance that arises while a
program is running, such as an attempt to
divide by zero.
Exceptions provide a way to transfer control
from one part of a program to another
C# exception handling is built upon four
keywords:
try, catch, finally, and throw.
try − A try block identifies a block of code for
which particular exceptions is activated. It is
followed by one or more catch blocks.
catch − A program catches an exception with an
exception handler at the place in a program
where you want to handle the problem. The catch
keyword indicates the catching of an exception.
finally − The finally block is used to execute a
given set of statements, whether an exception is
thrown or not thrown. For example, if you open a
file, it must be closed whether an exception is
raised or not.
throw − A program throws an exception when a
problem shows up. This is done using a throw
keyword.
Syntax
 Assuming a block raises an exception, a method catches an
exception using a combination of the try and catch keywords.
 A try/catch block is placed around the code that might generate an
exception.
 Code within a try/catch block is referred to as protected code, and
the syntax for using try/catch looks like the following −

try {
// statements causing exception
} catch( ExceptionName e1 ) {
// error handling code
} catch( ExceptionName e2 ) {
// error handling code
} catch( ExceptionName eN ) {
// error handling code
} finally {
// statements to be executed
}
 You can list down multiple catch statements to catch different type
of exceptions in case your try block raises more than one
exception in different situations.
Exception Classes in C#
C# exceptions are represented by classes.
The exception classes in C# are mainly directly
or indirectly derived from
the System.Exception class.
The System.ApplicationException class
supports exceptions generated by application
programs.
The System.SystemException class is the
base class for all predefined system exception.
System.IO.IOException- Handles I/O errors.
System.IndexOutOfRangeException -
Handles errors generated when a method
refers to an array index out of range.
System.ArrayTypeMismatchException-
Handles errors generated when type is
mismatched with the array type.
System.NullReferenceException- Handles
errors generated from referencing a null object.
System.DivideByZeroException - Handles
errors generated from dividing a dividend with
zero.
System.InvalidCastException -Handles
errors generated during typecasting.
System.OutOfMemoryException- Handles
errors generated from insufficient free memory.
System.StackOverflowException-Handles
errors generated from stack overflow.
Handling Exceptions
C# provides a structured solution to the exception
handling in the form of try and catch blocks.
Using these blocks the core program statements
are separated from the error-handling statements.
These error handling blocks are implemented
using the try, catch, and finally keywords.
Following is an example of throwing an exception
when dividing by zero condition occurs −
using System;
namespace ErrorHandlingApplication {
class DivNumbers {
int result;
DivNumbers()
{ result = 0; }
public void division(int num1, int num2) {
try {
result = num1 / num2;
} catch (DivideByZeroException e) {
Console.WriteLine("Exception caught: {0}", e);
} finally {
Console.WriteLine("Result: {0}", result);
}
}
static void Main(string[] args) {
DivNumbers d = new DivNumbers();
d.division(25, 0);
Console.ReadKey();
}
}
}
Throw keyword

The throw statement allows you to create a custom


error.
The throw statement is used together with an
exception class.
There are many exception classes available in C#:
ArithmeticException, FileNotFoundException,
IndexOutOfRangeException, TimeOutException, etc:
The throw creates an object of any valid exception
type using the new keyword.
The throw keyword cannot be used with any other
type which does not derive from the Exception
class.
static void checkAge(int age)
{
if (age < 18)
{
throw new ArithmeticException("Access denied - You
must be at least 18 years old.");
}
else
{
Console.WriteLine("Access granted - You are old
enough!");
}
}
static void Main(string[] args)
{
checkAge(15);
}

You might also like