SlideShare a Scribd company logo
1 of 29
UNIT III – PROGRAMMING
USING C#.NET
R SARASWATHI
SRI AKILANDESWARI WOMENS COLLEGE
DELEGATES AND EVENTS
Delegates – Declaring a Delegate – Defining
Delegate Methods – Creating and Invoking
Delegate Objects – Multicasting with
Delegates – Events – Event Sources –Event
Handlers – Events and Delegates.
Delegates
• Pass a function as a parameter.
• 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.
• Delegate just contains the details of a method.
• A delegate is a class that encapsulates a method signature.
• Although it can be used in any context, it often serves as the
basis for the event-handling model in C# and .NET.
Delegates
• Provides a good way to encapsulate the methods.
• Delegates are the library class in System namespace.
• These are the type-safe pointer of any method.
• Delegates are mainly used in implementing the call-back methods
and events.
• Delegates can be chained together as two or more methods can be
called on a single event.
• It doesn’t care about the class of the object that it references.
• Delegates can also be used in “anonymous methods” invocation.
Delegate
• There are three steps involved while
working with delegates:
– Declare a delegate
– Set a target method
– Invoke a delegate
Delegate
Singlecast delegate
• Singlecast delegate point to single method at a time. In
this the delegate is assigned to a single method at a
time. They are derived from System.Delegate class.
Multicast Delegate
• When a delegate is wrapped with more than one method
that is known as a multicast delegate.
• In C#, delegates are multicast, which means that they
can point to more than one function at a time. They are
derived from System.MulticastDelegate class.
Declaring a Delegate
[access modifier] delegate [return type] [delegate
name]([parameters])
• 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.
Declaring a Delegate
Example:
// "public" is the modifier
// "int" is return type
// "delegate1" is delegate name
// "(int G, int F, int G)" are the parameters
public delegate int delegate1(int G, int F, int
G);
public delegate void MyDelegate(string msg);
public delegate void DelegateExample();
Creating and Invoking
Delegate Objects
• After declaring a delegate, a delegate object is created
with the help of new keyword.
• Once a delegate is instantiated, a method call made to
the delegate is pass by the delegate to that method.
• The parameters passed to the delegate by the caller are
passed to the method, and the return value, if any, from
the method, is returned to the caller by the delegate.
• 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.
Creating and Invoking
Delegate Objects
• public delegate void printString(string s);
...
– printString ps1 = new
printString(WriteToScreen);
– printString ps2 = new printString(WriteToFile);
Creating and Invoking
Delegate Objects
Delegate1 GFG = new Delegate1(Geeks);
// here,
// " Delegate1 " is delegate name.
// "GFG" is instance_name
// "Geeks" is the calling method.
Delegate
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);
}
using System;
namespace GeeksForGeeks {
class Geeks {
public delegate void addnum(int a, int b);
public delegate void subnum(int a, int b);
public void sum(int a, int b)
{
Console.WriteLine("(100 + 40) = {0}", a + b);
}
public void subtract(int a, int b)
{
Console.WriteLine("(100 - 60) = {0}", a - b);
}
public static void Main(String []args)
{
Geeks obj = new Geeks();
addnum del_obj1 = new addnum(obj.sum);
subnum del_obj2 = new subnum(obj.subtract);
del_obj1(100, 40);
del_obj2(100, 60);
//del_obj1.Invoke(100, 40);
//del_obj2.Invoke(100, 60);
} }}
Delegate
Output:
• (100 + 40) = 140
• (100 - 60) = 40
Multicasting with Delegates
• Multicasting of delegate is an
extension of the normal
delegate(sometimes termed as Single
Cast Delegate).
• It helps the user to point more than
one method in a single call.
Multicasting with Delegates
Properties:
• Delegates are combined and when you
call a delegate then a complete list of
methods is called.
• All methods are called in First in First
Out(FIFO) order.
• ‘+’ or ‘+=’ Operator is used to add the
methods to delegates.
• ‘–’ or ‘-=’ Operator is used to remove the
methods from the delegates list.
Multicasting with Delegates
• Multicasting of delegate should have a
return type of Void otherwise it will
throw a runtime exception.
• Also, the multicasting of delegate will
return the value only from the last
method added in the multicast.
• Although, the other methods will be
executed successfully.
using System;
delegate int NumberChanger(int n);
namespace DelegateAppl
{
class TestDelegate { static int num = 10;
public static int AddNum(int p)
{
num += p; return num;
}
public static int MultNum(int q)
{
num *= q;
return num;
}
public static int getNum()
{
return num;
}
static void Main(string[] args)
{
//create delegate instances NumberChanger nc;
NumberChanger nc1 = new NumberChanger(AddNum);
NumberChanger nc2 = new NumberChanger(MultNum);
NumberChanger nc = nc1;
nc += nc2; //calling multicast
nc(5);
Console.WriteLine("Value of Num: {0}", getNum());
Console.ReadKey();
}} }
Events
• An event is a notification sent by an object to signal the
occurrence of an action. Events in .NET follow
the observer design pattern.
• The class who raises events is called Publisher, and the
class who receives the notification is called Subscriber.
• There can be multiple subscribers of a single event.
• Typically, a publisher raises an event when some action
occurred.
• The subscribers, who are interested in getting a
notification when an action occurred, should register
with an event and handle it.
Events
• In C#, an event is an encapsulated delegate.
• It is dependent on the delegate.
The delegate defines the signature for the event
handler method of the subscriber class.
Events
Events
public delegate void Notify(); // delegate
public class ProcessBusinessLogic
{
public event Notify ProcessCompleted; // event
public void StartProcess()
{
Console.WriteLine("Process Started!");
// some code here..
OnProcessCompleted();
}
protected virtual void OnProcessCompleted() //protected virtual
method
{
//if ProcessCompleted is not null then call delegate
ProcessCompleted?.Invoke();
} }
Events
using System;
namespace SampleApp
{
public delegate string MyDel(string str);
class EventProgram
{
event MyDel MyEvent;
public EventProgram()
{
this.MyEvent += new MyDel(this.WelcomeUser);
}
public string WelcomeUser(string username)
{
return "Welcome " + username;
}
static void Main(string[] args)
{
EventProgram obj1 = new EventProgram();
string result = obj1.MyEvent("Tutorials Point");
Console.WriteLine(result);
Event Sources
• Provides the ability to create events for
event tracing for Windows (ETW).
– Public class EventSource : Idisposable
• InheritanceObject
• EventSource
• DerivedMicrosoft.Extensions.Logging.
EventSource.LoggingEventSource
• ImplementsIDisposable
using System.Diagnostics.Tracing;
using System.Collections.Generic;
namespace Demo1
{
class MyCompanyEventSource : EventSource
{
public static MyCompanyEventSource Log = new MyCompanyEventSource();
public void Startup()
{ WriteEvent(1); }
public void OpenFileStart(string fileName){ WriteEvent(2, fileName); }
public void OpenFileStop() { WriteEvent(3); }
}
class Program
{
static void Main(string[] args)
{
string name = MyCompanyEventSource.GetName(typeof(MyCompanyEventSource));
IEnumerable<EventSource> eventSources = MyCompanyEventSource.GetSources();
MyCompanyEventSource.Log.Startup();
// ...
MyCompanyEventSource.Log.OpenFileStart("SomeFile");
// ...
MyCompanyEventSource.Log.OpenFileStop();
} } }
Event Handlers
• An event can be declared in two steps:
– Declare a delegate.
– Declare a variable of the delegate
with event keyword.
Example: Declaring an Event
• public delegate void Notify(); // delegate
public class ProcessBusinessLogic {
• public event Notify ProcessCompleted; //
event }
Event Handlers
public class ProcessBusinessLogic {
public event Notify ProcessCompleted;
// event
public void StartProcess() {
Console.WriteLine("Process Started!");
// some code here..
OnProcessCompleted();
}
protected virtual void OnProcessCompleted() //protected
virtual method
{ //if ProcessCompleted is not null then call delegate
ProcessCompleted?.Invoke();
} }
Event Handlers
Example: Consume an Event
class Program
{
public static void Main()
{
ProcessBusinessLogic bl = new ProcessBusinessLogic();
bl.ProcessCompleted += bl_ProcessCompleted;
// register with an event
bl.StartProcess(); } // event handler
public static void bl_ProcessCompleted()
{
Console.WriteLine("Process Completed!");
} }
Events and Delegates

More Related Content

What's hot

66781291 java-lab-manual
66781291 java-lab-manual66781291 java-lab-manual
66781291 java-lab-manualLaura Popovici
 
Java programming lab assignments
Java programming lab assignments Java programming lab assignments
Java programming lab assignments rajni kaushal
 
Navigating the xDD Alphabet Soup
Navigating the xDD Alphabet SoupNavigating the xDD Alphabet Soup
Navigating the xDD Alphabet SoupDror Helper
 
Swiss army knife Spring
Swiss army knife SpringSwiss army knife Spring
Swiss army knife SpringMario Fusco
 
C# for-java-developers
C# for-java-developersC# for-java-developers
C# for-java-developersDhaval Dalal
 
Procedures functions structures in VB.Net
Procedures  functions  structures in VB.NetProcedures  functions  structures in VB.Net
Procedures functions structures in VB.Nettjunicornfx
 
Lab manual object oriented technology (it 303 rgpv) (usefulsearch.org) (usef...
Lab manual object oriented technology (it 303 rgpv) (usefulsearch.org)  (usef...Lab manual object oriented technology (it 303 rgpv) (usefulsearch.org)  (usef...
Lab manual object oriented technology (it 303 rgpv) (usefulsearch.org) (usef...Make Mannan
 
Pragmatic functional refactoring with java 8
Pragmatic functional refactoring with java 8Pragmatic functional refactoring with java 8
Pragmatic functional refactoring with java 8RichardWarburton
 
Booting into functional programming
Booting into functional programmingBooting into functional programming
Booting into functional programmingDhaval Dalal
 
SystemVerilog OOP Ovm Features Summary
SystemVerilog OOP Ovm Features SummarySystemVerilog OOP Ovm Features Summary
SystemVerilog OOP Ovm Features SummaryAmal Khailtash
 

What's hot (20)

66781291 java-lab-manual
66781291 java-lab-manual66781291 java-lab-manual
66781291 java-lab-manual
 
Java codes
Java codesJava codes
Java codes
 
Java programming lab assignments
Java programming lab assignments Java programming lab assignments
Java programming lab assignments
 
Clean code
Clean codeClean code
Clean code
 
Refactoring
RefactoringRefactoring
Refactoring
 
Java programming-examples
Java programming-examplesJava programming-examples
Java programming-examples
 
Navigating the xDD Alphabet Soup
Navigating the xDD Alphabet SoupNavigating the xDD Alphabet Soup
Navigating the xDD Alphabet Soup
 
C storage classes
C storage classesC storage classes
C storage classes
 
Swiss army knife Spring
Swiss army knife SpringSwiss army knife Spring
Swiss army knife Spring
 
C# for-java-developers
C# for-java-developersC# for-java-developers
C# for-java-developers
 
Procedures functions structures in VB.Net
Procedures  functions  structures in VB.NetProcedures  functions  structures in VB.Net
Procedures functions structures in VB.Net
 
Lab manual object oriented technology (it 303 rgpv) (usefulsearch.org) (usef...
Lab manual object oriented technology (it 303 rgpv) (usefulsearch.org)  (usef...Lab manual object oriented technology (it 303 rgpv) (usefulsearch.org)  (usef...
Lab manual object oriented technology (it 303 rgpv) (usefulsearch.org) (usef...
 
Oop objects_classes
Oop objects_classesOop objects_classes
Oop objects_classes
 
Understanding Subroutines and Functions in VB6
Understanding Subroutines and Functions in VB6Understanding Subroutines and Functions in VB6
Understanding Subroutines and Functions in VB6
 
c++ lab manual
c++ lab manualc++ lab manual
c++ lab manual
 
Pragmatic functional refactoring with java 8
Pragmatic functional refactoring with java 8Pragmatic functional refactoring with java 8
Pragmatic functional refactoring with java 8
 
Clean code slide
Clean code slideClean code slide
Clean code slide
 
Java 8 Workshop
Java 8 WorkshopJava 8 Workshop
Java 8 Workshop
 
Booting into functional programming
Booting into functional programmingBooting into functional programming
Booting into functional programming
 
SystemVerilog OOP Ovm Features Summary
SystemVerilog OOP Ovm Features SummarySystemVerilog OOP Ovm Features Summary
SystemVerilog OOP Ovm Features Summary
 

Similar to PROGRAMMING USING C#.NET SARASWATHI RAMALINGAM

Delegates and events
Delegates and eventsDelegates and events
Delegates and eventsIblesoft
 
Csharp4 delegates lambda_and_events
Csharp4 delegates lambda_and_eventsCsharp4 delegates lambda_and_events
Csharp4 delegates lambda_and_eventsAbed Bukhari
 
CJP Unit-1 contd.pptx
CJP Unit-1 contd.pptxCJP Unit-1 contd.pptx
CJP Unit-1 contd.pptxRAJASEKHARV10
 
C# Delegates and Event Handling
C# Delegates and Event HandlingC# Delegates and Event Handling
C# Delegates and Event HandlingJussi Pohjolainen
 
Explain Delegates step by step.
Explain Delegates step by step.Explain Delegates step by step.
Explain Delegates step by step.Questpond
 
Review of c_sharp2_features_part_ii
Review of c_sharp2_features_part_iiReview of c_sharp2_features_part_ii
Review of c_sharp2_features_part_iiNico Ludwig
 
Csphtp1 06
Csphtp1 06Csphtp1 06
Csphtp1 06HUST
 
Delegates and Events in Dot net technology
Delegates and Events  in Dot net technologyDelegates and Events  in Dot net technology
Delegates and Events in Dot net technologyranjana dalwani
 
EContent_11_2023_04_09_11_30_38_Unit_3_Objects_and_Classespptx__2023_03_20_12...
EContent_11_2023_04_09_11_30_38_Unit_3_Objects_and_Classespptx__2023_03_20_12...EContent_11_2023_04_09_11_30_38_Unit_3_Objects_and_Classespptx__2023_03_20_12...
EContent_11_2023_04_09_11_30_38_Unit_3_Objects_and_Classespptx__2023_03_20_12...vekariyakashyap
 
Virtual function
Virtual functionVirtual function
Virtual functionzindadili
 

Similar to PROGRAMMING USING C#.NET SARASWATHI RAMALINGAM (20)

Delegates and events
Delegates and events   Delegates and events
Delegates and events
 
Delegates and events
Delegates and eventsDelegates and events
Delegates and events
 
Csharp4 delegates lambda_and_events
Csharp4 delegates lambda_and_eventsCsharp4 delegates lambda_and_events
Csharp4 delegates lambda_and_events
 
Diifeerences In C#
Diifeerences In C#Diifeerences In C#
Diifeerences In C#
 
Delegate
DelegateDelegate
Delegate
 
Methods in Java
Methods in JavaMethods in Java
Methods in Java
 
Legacy is Good
Legacy is GoodLegacy is Good
Legacy is Good
 
30csharp
30csharp30csharp
30csharp
 
30c
30c30c
30c
 
CJP Unit-1 contd.pptx
CJP Unit-1 contd.pptxCJP Unit-1 contd.pptx
CJP Unit-1 contd.pptx
 
C# Delegates and Event Handling
C# Delegates and Event HandlingC# Delegates and Event Handling
C# Delegates and Event Handling
 
Explain Delegates step by step.
Explain Delegates step by step.Explain Delegates step by step.
Explain Delegates step by step.
 
Object Oriented Programming with C++
Object Oriented Programming with C++Object Oriented Programming with C++
Object Oriented Programming with C++
 
Class 10
Class 10Class 10
Class 10
 
Review of c_sharp2_features_part_ii
Review of c_sharp2_features_part_iiReview of c_sharp2_features_part_ii
Review of c_sharp2_features_part_ii
 
C# Delegates
C# DelegatesC# Delegates
C# Delegates
 
Csphtp1 06
Csphtp1 06Csphtp1 06
Csphtp1 06
 
Delegates and Events in Dot net technology
Delegates and Events  in Dot net technologyDelegates and Events  in Dot net technology
Delegates and Events in Dot net technology
 
EContent_11_2023_04_09_11_30_38_Unit_3_Objects_and_Classespptx__2023_03_20_12...
EContent_11_2023_04_09_11_30_38_Unit_3_Objects_and_Classespptx__2023_03_20_12...EContent_11_2023_04_09_11_30_38_Unit_3_Objects_and_Classespptx__2023_03_20_12...
EContent_11_2023_04_09_11_30_38_Unit_3_Objects_and_Classespptx__2023_03_20_12...
 
Virtual function
Virtual functionVirtual function
Virtual function
 

More from SaraswathiRamalingam

Georg scheutz - Charles babbage - Saraswathi Ramalingam
Georg scheutz - Charles babbage - Saraswathi RamalingamGeorg scheutz - Charles babbage - Saraswathi Ramalingam
Georg scheutz - Charles babbage - Saraswathi RamalingamSaraswathiRamalingam
 
Dennis ritchie - SARASWATHI RAMALINGAM
Dennis ritchie - SARASWATHI RAMALINGAMDennis ritchie - SARASWATHI RAMALINGAM
Dennis ritchie - SARASWATHI RAMALINGAMSaraswathiRamalingam
 
Arithmetic expression INFIX TO POSTFIX CONVERTION saraswathi ramalingam
Arithmetic expression INFIX TO POSTFIX CONVERTION saraswathi ramalingamArithmetic expression INFIX TO POSTFIX CONVERTION saraswathi ramalingam
Arithmetic expression INFIX TO POSTFIX CONVERTION saraswathi ramalingamSaraswathiRamalingam
 
PROGRAMMING USING C# .NET - SARASWATHI RAMALINGAM
PROGRAMMING USING C# .NET - SARASWATHI RAMALINGAMPROGRAMMING USING C# .NET - SARASWATHI RAMALINGAM
PROGRAMMING USING C# .NET - SARASWATHI RAMALINGAMSaraswathiRamalingam
 
PROGRAMMING USING C# .NET - SARASWATHI RAMALINGAM
PROGRAMMING USING C# .NET - SARASWATHI RAMALINGAMPROGRAMMING USING C# .NET - SARASWATHI RAMALINGAM
PROGRAMMING USING C# .NET - SARASWATHI RAMALINGAMSaraswathiRamalingam
 
PROGRAMMING USING C# .NET - SARASWATHI RAMALINGAM
PROGRAMMING USING C# .NET - SARASWATHI RAMALINGAMPROGRAMMING USING C# .NET - SARASWATHI RAMALINGAM
PROGRAMMING USING C# .NET - SARASWATHI RAMALINGAMSaraswathiRamalingam
 
PROGRAMMING USING C# .NET - SARASWATHI RAMALINGAM
PROGRAMMING USING C# .NET - SARASWATHI RAMALINGAMPROGRAMMING USING C# .NET - SARASWATHI RAMALINGAM
PROGRAMMING USING C# .NET - SARASWATHI RAMALINGAMSaraswathiRamalingam
 
PROGRAMMING USING C# .NET - SARASWATHI RAMALINGAM
PROGRAMMING USING C# .NET - SARASWATHI RAMALINGAMPROGRAMMING USING C# .NET - SARASWATHI RAMALINGAM
PROGRAMMING USING C# .NET - SARASWATHI RAMALINGAMSaraswathiRamalingam
 
PROGRAMMING USING C# .NET - SARASWATHI RAMALINGAM
PROGRAMMING USING C# .NET - SARASWATHI RAMALINGAMPROGRAMMING USING C# .NET - SARASWATHI RAMALINGAM
PROGRAMMING USING C# .NET - SARASWATHI RAMALINGAMSaraswathiRamalingam
 
PROGRAMMING USING C# .NET - SARASWATHI RAMALINGAM
PROGRAMMING USING C# .NET - SARASWATHI RAMALINGAMPROGRAMMING USING C# .NET - SARASWATHI RAMALINGAM
PROGRAMMING USING C# .NET - SARASWATHI RAMALINGAMSaraswathiRamalingam
 
PROGRAMMING USING C# .NET - SARASWATHI RAMALINGAM
PROGRAMMING USING C# .NET - SARASWATHI RAMALINGAMPROGRAMMING USING C# .NET - SARASWATHI RAMALINGAM
PROGRAMMING USING C# .NET - SARASWATHI RAMALINGAMSaraswathiRamalingam
 
LAB PROGRAMS SARASWATHI RAMALINGAM
LAB PROGRAMS SARASWATHI RAMALINGAMLAB PROGRAMS SARASWATHI RAMALINGAM
LAB PROGRAMS SARASWATHI RAMALINGAMSaraswathiRamalingam
 

More from SaraswathiRamalingam (20)

MACINTOSH
MACINTOSHMACINTOSH
MACINTOSH
 
XSL - XML STYLE SHEET
XSL - XML STYLE SHEETXSL - XML STYLE SHEET
XSL - XML STYLE SHEET
 
XML - SAX
XML - SAXXML - SAX
XML - SAX
 
DOM-XML
DOM-XMLDOM-XML
DOM-XML
 
X FILES
X FILESX FILES
X FILES
 
XML SCHEMAS
XML SCHEMASXML SCHEMAS
XML SCHEMAS
 
XML
XMLXML
XML
 
XML DTD DOCUMENT TYPE DEFINITION
XML DTD DOCUMENT TYPE DEFINITIONXML DTD DOCUMENT TYPE DEFINITION
XML DTD DOCUMENT TYPE DEFINITION
 
Georg scheutz - Charles babbage - Saraswathi Ramalingam
Georg scheutz - Charles babbage - Saraswathi RamalingamGeorg scheutz - Charles babbage - Saraswathi Ramalingam
Georg scheutz - Charles babbage - Saraswathi Ramalingam
 
Dennis ritchie - SARASWATHI RAMALINGAM
Dennis ritchie - SARASWATHI RAMALINGAMDennis ritchie - SARASWATHI RAMALINGAM
Dennis ritchie - SARASWATHI RAMALINGAM
 
Arithmetic expression INFIX TO POSTFIX CONVERTION saraswathi ramalingam
Arithmetic expression INFIX TO POSTFIX CONVERTION saraswathi ramalingamArithmetic expression INFIX TO POSTFIX CONVERTION saraswathi ramalingam
Arithmetic expression INFIX TO POSTFIX CONVERTION saraswathi ramalingam
 
PROGRAMMING USING C# .NET - SARASWATHI RAMALINGAM
PROGRAMMING USING C# .NET - SARASWATHI RAMALINGAMPROGRAMMING USING C# .NET - SARASWATHI RAMALINGAM
PROGRAMMING USING C# .NET - SARASWATHI RAMALINGAM
 
PROGRAMMING USING C# .NET - SARASWATHI RAMALINGAM
PROGRAMMING USING C# .NET - SARASWATHI RAMALINGAMPROGRAMMING USING C# .NET - SARASWATHI RAMALINGAM
PROGRAMMING USING C# .NET - SARASWATHI RAMALINGAM
 
PROGRAMMING USING C# .NET - SARASWATHI RAMALINGAM
PROGRAMMING USING C# .NET - SARASWATHI RAMALINGAMPROGRAMMING USING C# .NET - SARASWATHI RAMALINGAM
PROGRAMMING USING C# .NET - SARASWATHI RAMALINGAM
 
PROGRAMMING USING C# .NET - SARASWATHI RAMALINGAM
PROGRAMMING USING C# .NET - SARASWATHI RAMALINGAMPROGRAMMING USING C# .NET - SARASWATHI RAMALINGAM
PROGRAMMING USING C# .NET - SARASWATHI RAMALINGAM
 
PROGRAMMING USING C# .NET - SARASWATHI RAMALINGAM
PROGRAMMING USING C# .NET - SARASWATHI RAMALINGAMPROGRAMMING USING C# .NET - SARASWATHI RAMALINGAM
PROGRAMMING USING C# .NET - SARASWATHI RAMALINGAM
 
PROGRAMMING USING C# .NET - SARASWATHI RAMALINGAM
PROGRAMMING USING C# .NET - SARASWATHI RAMALINGAMPROGRAMMING USING C# .NET - SARASWATHI RAMALINGAM
PROGRAMMING USING C# .NET - SARASWATHI RAMALINGAM
 
PROGRAMMING USING C# .NET - SARASWATHI RAMALINGAM
PROGRAMMING USING C# .NET - SARASWATHI RAMALINGAMPROGRAMMING USING C# .NET - SARASWATHI RAMALINGAM
PROGRAMMING USING C# .NET - SARASWATHI RAMALINGAM
 
PROGRAMMING USING C# .NET - SARASWATHI RAMALINGAM
PROGRAMMING USING C# .NET - SARASWATHI RAMALINGAMPROGRAMMING USING C# .NET - SARASWATHI RAMALINGAM
PROGRAMMING USING C# .NET - SARASWATHI RAMALINGAM
 
LAB PROGRAMS SARASWATHI RAMALINGAM
LAB PROGRAMS SARASWATHI RAMALINGAMLAB PROGRAMS SARASWATHI RAMALINGAM
LAB PROGRAMS SARASWATHI RAMALINGAM
 

Recently uploaded

Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Celine George
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 
Pharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfPharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfMahmoud M. Sallam
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting DataJhengPantaleon
 
Science 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsScience 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsKarinaGenton
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxRaymartEstabillo3
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxHistory Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxsocialsciencegdgrohi
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionSafetyChain Software
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 

Recently uploaded (20)

Staff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSDStaff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSD
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 
Pharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfPharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdf
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
 
Science 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsScience 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its Characteristics
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxHistory Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory Inspection
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 

PROGRAMMING USING C#.NET SARASWATHI RAMALINGAM

  • 1. UNIT III – PROGRAMMING USING C#.NET R SARASWATHI SRI AKILANDESWARI WOMENS COLLEGE
  • 2. DELEGATES AND EVENTS Delegates – Declaring a Delegate – Defining Delegate Methods – Creating and Invoking Delegate Objects – Multicasting with Delegates – Events – Event Sources –Event Handlers – Events and Delegates.
  • 3. Delegates • Pass a function as a parameter. • 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. • Delegate just contains the details of a method. • A delegate is a class that encapsulates a method signature. • Although it can be used in any context, it often serves as the basis for the event-handling model in C# and .NET.
  • 4. Delegates • Provides a good way to encapsulate the methods. • Delegates are the library class in System namespace. • These are the type-safe pointer of any method. • Delegates are mainly used in implementing the call-back methods and events. • Delegates can be chained together as two or more methods can be called on a single event. • It doesn’t care about the class of the object that it references. • Delegates can also be used in “anonymous methods” invocation.
  • 5. Delegate • There are three steps involved while working with delegates: – Declare a delegate – Set a target method – Invoke a delegate
  • 6. Delegate Singlecast delegate • Singlecast delegate point to single method at a time. In this the delegate is assigned to a single method at a time. They are derived from System.Delegate class. Multicast Delegate • When a delegate is wrapped with more than one method that is known as a multicast delegate. • In C#, delegates are multicast, which means that they can point to more than one function at a time. They are derived from System.MulticastDelegate class.
  • 7. Declaring a Delegate [access modifier] delegate [return type] [delegate name]([parameters]) • 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.
  • 8. Declaring a Delegate Example: // "public" is the modifier // "int" is return type // "delegate1" is delegate name // "(int G, int F, int G)" are the parameters public delegate int delegate1(int G, int F, int G); public delegate void MyDelegate(string msg); public delegate void DelegateExample();
  • 9. Creating and Invoking Delegate Objects • After declaring a delegate, a delegate object is created with the help of new keyword. • Once a delegate is instantiated, a method call made to the delegate is pass by the delegate to that method. • The parameters passed to the delegate by the caller are passed to the method, and the return value, if any, from the method, is returned to the caller by the delegate. • 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.
  • 10. Creating and Invoking Delegate Objects • public delegate void printString(string s); ... – printString ps1 = new printString(WriteToScreen); – printString ps2 = new printString(WriteToFile);
  • 11. Creating and Invoking Delegate Objects Delegate1 GFG = new Delegate1(Geeks); // here, // " Delegate1 " is delegate name. // "GFG" is instance_name // "Geeks" is the calling method.
  • 12. Delegate 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); }
  • 13. using System; namespace GeeksForGeeks { class Geeks { public delegate void addnum(int a, int b); public delegate void subnum(int a, int b); public void sum(int a, int b) { Console.WriteLine("(100 + 40) = {0}", a + b); } public void subtract(int a, int b) { Console.WriteLine("(100 - 60) = {0}", a - b); } public static void Main(String []args) { Geeks obj = new Geeks(); addnum del_obj1 = new addnum(obj.sum); subnum del_obj2 = new subnum(obj.subtract); del_obj1(100, 40); del_obj2(100, 60); //del_obj1.Invoke(100, 40); //del_obj2.Invoke(100, 60); } }}
  • 14. Delegate Output: • (100 + 40) = 140 • (100 - 60) = 40
  • 15. Multicasting with Delegates • Multicasting of delegate is an extension of the normal delegate(sometimes termed as Single Cast Delegate). • It helps the user to point more than one method in a single call.
  • 16. Multicasting with Delegates Properties: • Delegates are combined and when you call a delegate then a complete list of methods is called. • All methods are called in First in First Out(FIFO) order. • ‘+’ or ‘+=’ Operator is used to add the methods to delegates. • ‘–’ or ‘-=’ Operator is used to remove the methods from the delegates list.
  • 17. Multicasting with Delegates • Multicasting of delegate should have a return type of Void otherwise it will throw a runtime exception. • Also, the multicasting of delegate will return the value only from the last method added in the multicast. • Although, the other methods will be executed successfully.
  • 18. using System; delegate int NumberChanger(int n); namespace DelegateAppl { class TestDelegate { static int num = 10; public static int AddNum(int p) { num += p; return num; } public static int MultNum(int q) { num *= q; return num; } public static int getNum() { return num; } static void Main(string[] args) { //create delegate instances NumberChanger nc; NumberChanger nc1 = new NumberChanger(AddNum); NumberChanger nc2 = new NumberChanger(MultNum); NumberChanger nc = nc1; nc += nc2; //calling multicast nc(5); Console.WriteLine("Value of Num: {0}", getNum()); Console.ReadKey(); }} }
  • 19. Events • An event is a notification sent by an object to signal the occurrence of an action. Events in .NET follow the observer design pattern. • The class who raises events is called Publisher, and the class who receives the notification is called Subscriber. • There can be multiple subscribers of a single event. • Typically, a publisher raises an event when some action occurred. • The subscribers, who are interested in getting a notification when an action occurred, should register with an event and handle it.
  • 20. Events • In C#, an event is an encapsulated delegate. • It is dependent on the delegate. The delegate defines the signature for the event handler method of the subscriber class.
  • 22. Events public delegate void Notify(); // delegate public class ProcessBusinessLogic { public event Notify ProcessCompleted; // event public void StartProcess() { Console.WriteLine("Process Started!"); // some code here.. OnProcessCompleted(); } protected virtual void OnProcessCompleted() //protected virtual method { //if ProcessCompleted is not null then call delegate ProcessCompleted?.Invoke(); } }
  • 23. Events using System; namespace SampleApp { public delegate string MyDel(string str); class EventProgram { event MyDel MyEvent; public EventProgram() { this.MyEvent += new MyDel(this.WelcomeUser); } public string WelcomeUser(string username) { return "Welcome " + username; } static void Main(string[] args) { EventProgram obj1 = new EventProgram(); string result = obj1.MyEvent("Tutorials Point"); Console.WriteLine(result);
  • 24. Event Sources • Provides the ability to create events for event tracing for Windows (ETW). – Public class EventSource : Idisposable • InheritanceObject • EventSource • DerivedMicrosoft.Extensions.Logging. EventSource.LoggingEventSource • ImplementsIDisposable
  • 25. using System.Diagnostics.Tracing; using System.Collections.Generic; namespace Demo1 { class MyCompanyEventSource : EventSource { public static MyCompanyEventSource Log = new MyCompanyEventSource(); public void Startup() { WriteEvent(1); } public void OpenFileStart(string fileName){ WriteEvent(2, fileName); } public void OpenFileStop() { WriteEvent(3); } } class Program { static void Main(string[] args) { string name = MyCompanyEventSource.GetName(typeof(MyCompanyEventSource)); IEnumerable<EventSource> eventSources = MyCompanyEventSource.GetSources(); MyCompanyEventSource.Log.Startup(); // ... MyCompanyEventSource.Log.OpenFileStart("SomeFile"); // ... MyCompanyEventSource.Log.OpenFileStop(); } } }
  • 26. Event Handlers • An event can be declared in two steps: – Declare a delegate. – Declare a variable of the delegate with event keyword. Example: Declaring an Event • public delegate void Notify(); // delegate public class ProcessBusinessLogic { • public event Notify ProcessCompleted; // event }
  • 27. Event Handlers public class ProcessBusinessLogic { public event Notify ProcessCompleted; // event public void StartProcess() { Console.WriteLine("Process Started!"); // some code here.. OnProcessCompleted(); } protected virtual void OnProcessCompleted() //protected virtual method { //if ProcessCompleted is not null then call delegate ProcessCompleted?.Invoke(); } }
  • 28. Event Handlers Example: Consume an Event class Program { public static void Main() { ProcessBusinessLogic bl = new ProcessBusinessLogic(); bl.ProcessCompleted += bl_ProcessCompleted; // register with an event bl.StartProcess(); } // event handler public static void bl_ProcessCompleted() { Console.WriteLine("Process Completed!"); } }