SlideShare una empresa de Scribd logo
1 de 8
Delegates & Events Ch. Vishwa Mohan Freelance Software Consultant & Corporate Trainer
Delegates In .NET the concept of function pointers are implemented in the form of delegates. Unlike C function pointers the .NET delegates are type-safe.  With the help of delegates you can pass one of the method as a argument to a function call.  In creating threads you will pass the method as one of argument.  In GUI environment for handling events also you can use it.  In .NET Delegates are defined with delegate class. Using the delegates is a two stage process.  Define the delegate  Create one or more instances of the delegate.  Delegates in C# always syntactically take one parameter constructor. The parameter being the method that delegate refers. You can invoke a delegate either by supplying brackets to delegate object on calling Invoke method on it.
Delegates You can apply any of the access modifier to delegate.  publicdelegate void MyMethodInvoker(int x);  //Also apply private, etc.., An instance of a given delegate can refers to any instance or static method on any object of any type, provided that the signature of method should math the signature of delegate. (So type-safety).  Delegates are implemented as classes derived from the class System.MulticastDelegate which itself derived from System.Delegate. Delegate Inference: You can also create a delegate and assigning method to it as follow: MyMethodInvokerobjDelegate = MySquareFunc;   //Delegate Inference Anonymous Methods: An anonymous method is a block of code that can be used as the parameter of the delegates instead of method.  The syntax for defining delegate with anonymous method doesn’t change. While instantiating a delegate you need to supply code block instead of method name.
Multicast Delegates If you wrap a delegate with more then one method that delegate is called Multicast delegate.  If a multi cast delegate is invoked, it will successively call each method in order they are registered with delegate.  To make sense the delegate signature should return a void;  A multicast delegate is a class derived from System.MulticastDelegate which in tern derived from System.Delegate.  Let us define a delegate like below: delegate voidMathOpDelegate(double val); 		MathOpDelegate d1 = MathClass.MultiplyByTwo;  		MathOpDelegate d2 = MathClass.Square;  		MathOpDelegate mathOperations = d1 + d2;  If one of the method invoked by a delegate thrown an exception, the complete iteration stops. To address this problem you can get list of member functions supported by multicast delegate and invoke them one by one.
Events Events in the .NET are based on delegate model.  The event model in .NET Framework is based on having an event delegate that connects an event with its handler. To raise an event two events are needed.  ,[object Object]
A class that holds the event data. (Eg: EventArgs)Events enable a class or object to notify other classes or objects when something of interest occurs.  The class that sends the event is called as publisher and the class that receives the event called as subscriber.  An event can have multiple subscribers.  A subscriber can handle multiple events from multiple publishers. Events that have no subscribers are never called.
Events Inside the .NET framework, the EventHandler is a predefined delegate that specially represents event handler method for an event that does not generate data. Its definition inside .NET Framework as below: public delegate void EventHandler( Object sender, EventArgs e )  If your event does generate data then use EventHandler<TEvtArgs> generic delegate class and you can pass custom event data type as parameter.  	public delegate void EventHandler<TEventArgs>( Object sender, 					TEventArgs e ) where TEventArgs : EventArgs In .NET framework events are based on the EventHandler delegate and the EventArgs base class.  public delegate void AlarmEventHandler(object sender, AlarmEventArgs e);  These events delegates in the .NET framework has two parameters the source that raised the event and the data that raised the event.  Similar to multicast delegates, event handlers can’t return a value always returns void. Because event handlers also wrap up more then one handler.
Generic Delegates With generic delegates the parameter of the delegate can be defined later. Simple delegate examples is given below:  public delegate void Del<T>(T item);  public delegateT2  Action<T1, T2>(T1  tVal);  Nullable<T>: Suppose if you are instantiated as Nullable<int> x. The variable x can now be used like int and also you can assign null to it. Nullable<int> x; //or int? x; 		if(x.HasValue) 		x = 5;					     int y = x.Value;  		x += 20; 					  x = null; EventHandler<TEventArgs>: With Windows forms, Web Applications delegates many different event handlers are defined.  ArraySegment<T>:  This structure is used to represent a segment of an array. The offset and count of segment is stored in this structure.  Benefit of ArraySegment is you can pass it to method as a argument.  Take note, ArraySegment don’t make copy of elements of array. It just refers it.

Más contenido relacionado

La actualidad más candente

Evolution of C# delegates
Evolution of C# delegatesEvolution of C# delegates
Evolution of C# delegatesmbaric
 
C# Delegates and Event Handling
C# Delegates and Event HandlingC# Delegates and Event Handling
C# Delegates and Event HandlingJussi Pohjolainen
 
Lambda Expressions in C# From Beginner To Expert - Jaliya Udagedara
Lambda Expressions in C# From Beginner To Expert - Jaliya UdagedaraLambda Expressions in C# From Beginner To Expert - Jaliya Udagedara
Lambda Expressions in C# From Beginner To Expert - Jaliya UdagedaraJaliya Udagedara
 
Krazykoder struts2 annotations
Krazykoder struts2 annotationsKrazykoder struts2 annotations
Krazykoder struts2 annotationsKrazy Koder
 
Objects and classes in Visual Basic
Objects and classes in Visual BasicObjects and classes in Visual Basic
Objects and classes in Visual BasicSangeetha Sg
 
Module 12 aggregation, namespaces, and advanced scope
Module 12 aggregation, namespaces, and advanced scopeModule 12 aggregation, namespaces, and advanced scope
Module 12 aggregation, namespaces, and advanced scopePrem Kumar Badri
 
C Sharp: Basic to Intermediate Part 01
C Sharp: Basic to Intermediate Part 01C Sharp: Basic to Intermediate Part 01
C Sharp: Basic to Intermediate Part 01Zafor Iqbal
 
C++ Object oriented concepts & programming
C++ Object oriented concepts & programmingC++ Object oriented concepts & programming
C++ Object oriented concepts & programmingnirajmandaliya
 
Basic elements of java
Basic elements of java Basic elements of java
Basic elements of java Ahmad Idrees
 
Synapseindia strcture of dotnet development part 2
Synapseindia strcture of dotnet development part 2Synapseindia strcture of dotnet development part 2
Synapseindia strcture of dotnet development part 2Synapseindiappsdevelopment
 
Object oriented programming using c++
Object oriented programming using c++Object oriented programming using c++
Object oriented programming using c++Hoang Nguyen
 

La actualidad más candente (20)

Delegates and events in C#
Delegates and events in C#Delegates and events in C#
Delegates and events in C#
 
Evolution of C# delegates
Evolution of C# delegatesEvolution of C# delegates
Evolution of C# delegates
 
C# Delegates and Event Handling
C# Delegates and Event HandlingC# Delegates and Event Handling
C# Delegates and Event Handling
 
Lambda Expressions in C# From Beginner To Expert - Jaliya Udagedara
Lambda Expressions in C# From Beginner To Expert - Jaliya UdagedaraLambda Expressions in C# From Beginner To Expert - Jaliya Udagedara
Lambda Expressions in C# From Beginner To Expert - Jaliya Udagedara
 
Interface
InterfaceInterface
Interface
 
Krazykoder struts2 annotations
Krazykoder struts2 annotationsKrazykoder struts2 annotations
Krazykoder struts2 annotations
 
Objects and classes in Visual Basic
Objects and classes in Visual BasicObjects and classes in Visual Basic
Objects and classes in Visual Basic
 
Intake 37 5
Intake 37 5Intake 37 5
Intake 37 5
 
Module 12 aggregation, namespaces, and advanced scope
Module 12 aggregation, namespaces, and advanced scopeModule 12 aggregation, namespaces, and advanced scope
Module 12 aggregation, namespaces, and advanced scope
 
Active Object
Active ObjectActive Object
Active Object
 
C Sharp: Basic to Intermediate Part 01
C Sharp: Basic to Intermediate Part 01C Sharp: Basic to Intermediate Part 01
C Sharp: Basic to Intermediate Part 01
 
C++ Object oriented concepts & programming
C++ Object oriented concepts & programmingC++ Object oriented concepts & programming
C++ Object oriented concepts & programming
 
Constructors and Method Overloading
Constructors and Method OverloadingConstructors and Method Overloading
Constructors and Method Overloading
 
Intake 37 6
Intake 37 6Intake 37 6
Intake 37 6
 
Intake 37 4
Intake 37 4Intake 37 4
Intake 37 4
 
Intake 37 2
Intake 37 2Intake 37 2
Intake 37 2
 
Basic elements of java
Basic elements of java Basic elements of java
Basic elements of java
 
Synapseindia strcture of dotnet development part 2
Synapseindia strcture of dotnet development part 2Synapseindia strcture of dotnet development part 2
Synapseindia strcture of dotnet development part 2
 
Inheritance
InheritanceInheritance
Inheritance
 
Object oriented programming using c++
Object oriented programming using c++Object oriented programming using c++
Object oriented programming using c++
 

Destacado

C# Delegates, Events, Lambda
C# Delegates, Events, LambdaC# Delegates, Events, Lambda
C# Delegates, Events, LambdaJussi Pohjolainen
 
C# Starter L06-Delegates, Event Handling and Extension Methods
C# Starter L06-Delegates, Event Handling and Extension MethodsC# Starter L06-Delegates, Event Handling and Extension Methods
C# Starter L06-Delegates, Event Handling and Extension MethodsMohammad Shaker
 
Introduction to PHP
Introduction to PHPIntroduction to PHP
Introduction to PHPBradley Holt
 
ASP.NET Tutorial - Presentation 1
ASP.NET Tutorial - Presentation 1ASP.NET Tutorial - Presentation 1
ASP.NET Tutorial - Presentation 1Kumar S
 

Destacado (6)

C# Delegates, Events, Lambda
C# Delegates, Events, LambdaC# Delegates, Events, Lambda
C# Delegates, Events, Lambda
 
C# Starter L06-Delegates, Event Handling and Extension Methods
C# Starter L06-Delegates, Event Handling and Extension MethodsC# Starter L06-Delegates, Event Handling and Extension Methods
C# Starter L06-Delegates, Event Handling and Extension Methods
 
C# Generics
C# GenericsC# Generics
C# Generics
 
Introduction to PHP
Introduction to PHPIntroduction to PHP
Introduction to PHP
 
ASP.NET Tutorial - Presentation 1
ASP.NET Tutorial - Presentation 1ASP.NET Tutorial - Presentation 1
ASP.NET Tutorial - Presentation 1
 
Slideshare ppt
Slideshare pptSlideshare ppt
Slideshare ppt
 

Similar a Delegates and events

PATTERNS06 - The .NET Event Model
PATTERNS06 - The .NET Event ModelPATTERNS06 - The .NET Event Model
PATTERNS06 - The .NET Event ModelMichael Heron
 
Csharp4 delegates lambda_and_events
Csharp4 delegates lambda_and_eventsCsharp4 delegates lambda_and_events
Csharp4 delegates lambda_and_eventsAbed Bukhari
 
PROGRAMMING USING C#.NET SARASWATHI RAMALINGAM
PROGRAMMING USING C#.NET SARASWATHI RAMALINGAMPROGRAMMING USING C#.NET SARASWATHI RAMALINGAM
PROGRAMMING USING C#.NET SARASWATHI RAMALINGAMSaraswathiRamalingam
 
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
 
Working Effectively With Legacy Code
Working Effectively With Legacy CodeWorking Effectively With Legacy Code
Working Effectively With Legacy CodeNaresh Jain
 
Oop2011 actor presentation_stal
Oop2011 actor presentation_stalOop2011 actor presentation_stal
Oop2011 actor presentation_stalMichael Stal
 
Dr Jammi Ashok - Introduction to Java Material (OOPs)
 Dr Jammi Ashok - Introduction to Java Material (OOPs) Dr Jammi Ashok - Introduction to Java Material (OOPs)
Dr Jammi Ashok - Introduction to Java Material (OOPs)jammiashok123
 
Advanced programming topics asma
Advanced programming topics asmaAdvanced programming topics asma
Advanced programming topics asmaAbdullahJana
 
Application package
Application packageApplication package
Application packageJAYAARC
 
Java căn bản - Chapter7
Java căn bản - Chapter7Java căn bản - Chapter7
Java căn bản - Chapter7Vince Vo
 
Chapter 7 - Defining Your Own Classes - Part II
Chapter 7 - Defining Your Own Classes - Part IIChapter 7 - Defining Your Own Classes - Part II
Chapter 7 - Defining Your Own Classes - Part IIEduardo Bergavera
 
Events: The Object Oriented Hook System.
Events: The Object Oriented Hook System.Events: The Object Oriented Hook System.
Events: The Object Oriented Hook System.Nida Ismail Shah
 

Similar a Delegates and events (20)

PATTERNS06 - The .NET Event Model
PATTERNS06 - The .NET Event ModelPATTERNS06 - The .NET Event Model
PATTERNS06 - The .NET Event Model
 
Csharp4 delegates lambda_and_events
Csharp4 delegates lambda_and_eventsCsharp4 delegates lambda_and_events
Csharp4 delegates lambda_and_events
 
PROGRAMMING USING C#.NET SARASWATHI RAMALINGAM
PROGRAMMING USING C#.NET SARASWATHI RAMALINGAMPROGRAMMING USING C#.NET SARASWATHI RAMALINGAM
PROGRAMMING USING C#.NET SARASWATHI RAMALINGAM
 
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
 
Vb.net iv
Vb.net ivVb.net iv
Vb.net iv
 
ax2012
 ax2012 ax2012
ax2012
 
Diifeerences In C#
Diifeerences In C#Diifeerences In C#
Diifeerences In C#
 
Working Effectively With Legacy Code
Working Effectively With Legacy CodeWorking Effectively With Legacy Code
Working Effectively With Legacy Code
 
Oop2011 actor presentation_stal
Oop2011 actor presentation_stalOop2011 actor presentation_stal
Oop2011 actor presentation_stal
 
Dr Jammi Ashok - Introduction to Java Material (OOPs)
 Dr Jammi Ashok - Introduction to Java Material (OOPs) Dr Jammi Ashok - Introduction to Java Material (OOPs)
Dr Jammi Ashok - Introduction to Java Material (OOPs)
 
Advanced programming topics asma
Advanced programming topics asmaAdvanced programming topics asma
Advanced programming topics asma
 
Application package
Application packageApplication package
Application package
 
Ext Js Events
Ext Js EventsExt Js Events
Ext Js Events
 
Ext Js Events
Ext Js EventsExt Js Events
Ext Js Events
 
Java căn bản - Chapter7
Java căn bản - Chapter7Java căn bản - Chapter7
Java căn bản - Chapter7
 
Chapter 7 - Defining Your Own Classes - Part II
Chapter 7 - Defining Your Own Classes - Part IIChapter 7 - Defining Your Own Classes - Part II
Chapter 7 - Defining Your Own Classes - Part II
 
Events: The Object Oriented Hook System.
Events: The Object Oriented Hook System.Events: The Object Oriented Hook System.
Events: The Object Oriented Hook System.
 
Csharp
CsharpCsharp
Csharp
 
TY.BSc.IT Java QB U1
TY.BSc.IT Java QB U1TY.BSc.IT Java QB U1
TY.BSc.IT Java QB U1
 
Unit 6 Java
Unit 6 JavaUnit 6 Java
Unit 6 Java
 

Más de Iblesoft

Ms sql server ii
Ms sql server  iiMs sql server  ii
Ms sql server iiIblesoft
 
MS SQL Server 1
MS SQL Server 1MS SQL Server 1
MS SQL Server 1Iblesoft
 
Master pages ppt
Master pages pptMaster pages ppt
Master pages pptIblesoft
 
State management
State managementState management
State managementIblesoft
 
State management
State managementState management
State managementIblesoft
 
Validation controls ppt
Validation controls pptValidation controls ppt
Validation controls pptIblesoft
 
Generics n delegates
Generics n delegatesGenerics n delegates
Generics n delegatesIblesoft
 
Data controls ppt
Data controls pptData controls ppt
Data controls pptIblesoft
 
Microsoft.net architecturte
Microsoft.net architecturteMicrosoft.net architecturte
Microsoft.net architecturteIblesoft
 
Asp.net architecture
Asp.net architectureAsp.net architecture
Asp.net architectureIblesoft
 
Javascript
JavascriptJavascript
JavascriptIblesoft
 
Exception handling
Exception handlingException handling
Exception handlingIblesoft
 

Más de Iblesoft (17)

Ms sql server ii
Ms sql server  iiMs sql server  ii
Ms sql server ii
 
MS SQL Server 1
MS SQL Server 1MS SQL Server 1
MS SQL Server 1
 
Master pages ppt
Master pages pptMaster pages ppt
Master pages ppt
 
State management
State managementState management
State management
 
State management
State managementState management
State management
 
Validation controls ppt
Validation controls pptValidation controls ppt
Validation controls ppt
 
Controls
ControlsControls
Controls
 
Ado.net
Ado.netAdo.net
Ado.net
 
Generics n delegates
Generics n delegatesGenerics n delegates
Generics n delegates
 
Ajaxppt
AjaxpptAjaxppt
Ajaxppt
 
Data controls ppt
Data controls pptData controls ppt
Data controls ppt
 
Microsoft.net architecturte
Microsoft.net architecturteMicrosoft.net architecturte
Microsoft.net architecturte
 
Asp.net architecture
Asp.net architectureAsp.net architecture
Asp.net architecture
 
Generics
GenericsGenerics
Generics
 
Javascript
JavascriptJavascript
Javascript
 
Html ppt
Html pptHtml ppt
Html ppt
 
Exception handling
Exception handlingException handling
Exception handling
 

Último

On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsMebane Rash
 
Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - Englishneillewis46
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsTechSoup
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfagholdier
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxDenish Jangid
 
ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701bronxfugly43
 
Single or Multiple melodic lines structure
Single or Multiple melodic lines structureSingle or Multiple melodic lines structure
Single or Multiple melodic lines structuredhanjurrannsibayan2
 
Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...Association for Project Management
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfPoh-Sun Goh
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024Elizabeth Walsh
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...christianmathematics
 
Vishram Singh - Textbook of Anatomy Upper Limb and Thorax.. Volume 1 (1).pdf
Vishram Singh - Textbook of Anatomy  Upper Limb and Thorax.. Volume 1 (1).pdfVishram Singh - Textbook of Anatomy  Upper Limb and Thorax.. Volume 1 (1).pdf
Vishram Singh - Textbook of Anatomy Upper Limb and Thorax.. Volume 1 (1).pdfssuserdda66b
 
SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentationcamerronhm
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfNirmal Dwivedi
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...ZurliaSoop
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxRamakrishna Reddy Bijjam
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxVishalSingh1417
 
Towards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxTowards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxJisc
 

Último (20)

On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - English
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701
 
Single or Multiple melodic lines structure
Single or Multiple melodic lines structureSingle or Multiple melodic lines structure
Single or Multiple melodic lines structure
 
Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdf
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
Vishram Singh - Textbook of Anatomy Upper Limb and Thorax.. Volume 1 (1).pdf
Vishram Singh - Textbook of Anatomy  Upper Limb and Thorax.. Volume 1 (1).pdfVishram Singh - Textbook of Anatomy  Upper Limb and Thorax.. Volume 1 (1).pdf
Vishram Singh - Textbook of Anatomy Upper Limb and Thorax.. Volume 1 (1).pdf
 
SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentation
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
Spatium Project Simulation student brief
Spatium Project Simulation student briefSpatium Project Simulation student brief
Spatium Project Simulation student brief
 
Towards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxTowards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptx
 

Delegates and events

  • 1. Delegates & Events Ch. Vishwa Mohan Freelance Software Consultant & Corporate Trainer
  • 2. Delegates In .NET the concept of function pointers are implemented in the form of delegates. Unlike C function pointers the .NET delegates are type-safe. With the help of delegates you can pass one of the method as a argument to a function call. In creating threads you will pass the method as one of argument. In GUI environment for handling events also you can use it. In .NET Delegates are defined with delegate class. Using the delegates is a two stage process. Define the delegate Create one or more instances of the delegate. Delegates in C# always syntactically take one parameter constructor. The parameter being the method that delegate refers. You can invoke a delegate either by supplying brackets to delegate object on calling Invoke method on it.
  • 3. Delegates You can apply any of the access modifier to delegate. publicdelegate void MyMethodInvoker(int x); //Also apply private, etc.., An instance of a given delegate can refers to any instance or static method on any object of any type, provided that the signature of method should math the signature of delegate. (So type-safety). Delegates are implemented as classes derived from the class System.MulticastDelegate which itself derived from System.Delegate. Delegate Inference: You can also create a delegate and assigning method to it as follow: MyMethodInvokerobjDelegate = MySquareFunc; //Delegate Inference Anonymous Methods: An anonymous method is a block of code that can be used as the parameter of the delegates instead of method. The syntax for defining delegate with anonymous method doesn’t change. While instantiating a delegate you need to supply code block instead of method name.
  • 4. Multicast Delegates If you wrap a delegate with more then one method that delegate is called Multicast delegate. If a multi cast delegate is invoked, it will successively call each method in order they are registered with delegate. To make sense the delegate signature should return a void; A multicast delegate is a class derived from System.MulticastDelegate which in tern derived from System.Delegate. Let us define a delegate like below: delegate voidMathOpDelegate(double val); MathOpDelegate d1 = MathClass.MultiplyByTwo; MathOpDelegate d2 = MathClass.Square; MathOpDelegate mathOperations = d1 + d2; If one of the method invoked by a delegate thrown an exception, the complete iteration stops. To address this problem you can get list of member functions supported by multicast delegate and invoke them one by one.
  • 5.
  • 6. A class that holds the event data. (Eg: EventArgs)Events enable a class or object to notify other classes or objects when something of interest occurs. The class that sends the event is called as publisher and the class that receives the event called as subscriber. An event can have multiple subscribers. A subscriber can handle multiple events from multiple publishers. Events that have no subscribers are never called.
  • 7. Events Inside the .NET framework, the EventHandler is a predefined delegate that specially represents event handler method for an event that does not generate data. Its definition inside .NET Framework as below: public delegate void EventHandler( Object sender, EventArgs e ) If your event does generate data then use EventHandler<TEvtArgs> generic delegate class and you can pass custom event data type as parameter. public delegate void EventHandler<TEventArgs>( Object sender, TEventArgs e ) where TEventArgs : EventArgs In .NET framework events are based on the EventHandler delegate and the EventArgs base class. public delegate void AlarmEventHandler(object sender, AlarmEventArgs e); These events delegates in the .NET framework has two parameters the source that raised the event and the data that raised the event. Similar to multicast delegates, event handlers can’t return a value always returns void. Because event handlers also wrap up more then one handler.
  • 8. Generic Delegates With generic delegates the parameter of the delegate can be defined later. Simple delegate examples is given below: public delegate void Del<T>(T item); public delegateT2 Action<T1, T2>(T1 tVal); Nullable<T>: Suppose if you are instantiated as Nullable<int> x. The variable x can now be used like int and also you can assign null to it. Nullable<int> x; //or int? x; if(x.HasValue) x = 5; int y = x.Value; x += 20; x = null; EventHandler<TEventArgs>: With Windows forms, Web Applications delegates many different event handlers are defined. ArraySegment<T>: This structure is used to represent a segment of an array. The offset and count of segment is stored in this structure. Benefit of ArraySegment is you can pass it to method as a argument. Take note, ArraySegment don’t make copy of elements of array. It just refers it.