SlideShare a Scribd company logo
Delegate
Delegate
• A delegate provides a way to encapsulate
a method.
• An event is a notification that some
action has occurred.
• Delegates and events are related because
an event is built upon a delegate.
• A delegate is an object that can refer to
a method.
• when you create a delegate, you are
creating an object that can hold a
reference to a method.
• Furthermore, the method can be called
through this reference.
• A delegate can invoke the method to which
it refers.
• A delegate in C# is similar to a function
pointer in C/C++.
• A delegate type is declared using the
keyword delegate.
delegate return-type name (parameter-list );
• return-type is the type of value returned
by the methods that the delegate will be
calling.
• The name of the delegate is specified by
name.
• The parameters required by the methods
called through the delegate are specified
in the parameter-list.
• A delegate instance (Object) can refer
to and call methods whose return type
and parameter list match those
specified by the delegate declaration.
• The method can be either an instance
method associated with an object or a
static method associated with a class.
using System;
delegate string StrMod(string str);
class DelegateTest {
static string ReplaceSpaces(string s) {
Console.WriteLine("Replacing spaces with
hyphens.");
return s.Replace(' ', '-');
}
static string RemoveSpaces(string s) {
string temp = "";
int i;
Console.WriteLine("Removing spaces.")
for(i=0; i < s.Length; i++)
if(s[i] != ' ') temp += s[i];
return temp;
}
static string Reverse(string s) {
string temp = "";
int i, j;
Console.WriteLine("Reversing string.");
for(j=0, i=s.Length-1; i >= 0; i--, j++)
temp += s[i];
return temp;
}
static void Main() {
StrMod strOp = new
StrMod(ReplaceSpaces);
string str;
str = strOp("This is a test.");
Console.WriteLine("Resulting string: " + str);
Console.WriteLine();
strOp2 = new StrMod(RemoveSpaces);
str = strOp2("This is a test.");
Console.WriteLine("Resulting string: " + str);
strOp = new StrMod(Reverse);
str = strOp("This is a test.");
Console.WriteLine("Resulting string: " + str);
}
}
//output
Replacing spaces with hyphens.
Resulting string: This-is-a-test.
Removing spaces.
Resulting string: Thisisatest.
Reversing string.
Resulting string: .tset a si sihT
Delegate Method Group
Conversion
• Since version 2.0, C# has included an
option that significantly simplifies the
syntax that assigns a method to a
delegate.
• This feature is called method group
conversion, and it allows you to simply
assign the name of a method to a
delegate, without using new or explicitly
invoking the delegate’s constructor.
// use method group conversion
StrMod strOp = ReplaceSpaces;
string str;
// Call methods through the delegate.
str = strOp("This is a test.");
Console.WriteLine("Resulting string: " +
str);
Console.WriteLine();
Instance Methods as Delegates
delegate string StrMod(string str);
class StringOps {
public string ReplaceSpaces(string s) {
Console.WriteLine("Replacing spaces
with hyphens.");
return s.Replace(' ', '-');
}
public string RemoveSpaces(string s) {
string temp = "";
int i;
Console.WriteLine("Removing spaces.");
for(i=0; i < s.Length; i++)
if(s[i] != ' ') temp += s[i];
return temp;
}
public string Reverse(string s) {
string temp = "";
int i, j;
Console.WriteLine("Reversing string.");
for(j=0, i=s.Length-1; i >= 0; i--, j++)
temp += s[i];
return temp;
}
}
class DelegateTest {
static void Main() {
StringOps so = new StringOps();
// Initialize a delegate.
StrMod strOp = so.ReplaceSpaces;
string str;
// Call methods through delegates.
str = strOp("This is a test.");
Console.WriteLine("Resulting string: " +
str);
Console.WriteLine();
strOp = so.RemoveSpaces;
str = strOp("This is a test.");
Console.WriteLine("Resulting string: " +
str);
Console.WriteLine();
strOp = so.Reverse;
str = strOp("This is a test.");
Console.WriteLine("Resulting string: " +
str);
}}
Multicasting
• One of the most exciting features of a
delegate is its support for multicasting.
• Multicasting is the ability to create an
invocation list, or chain, of methods
that will be automatically called when a
delegate is invoked.
• Such a chain is very easy to create.
• Simply instantiate a delegate, and then use
the + or += operator to add methods to the
chain.
• To remove a method, use – or – =.
• If the delegate returns a value, then the value
returned by the last method in the list
becomes the return value of the entire
delegate invocation.
• Thus, a delegate that makes use of
multicasting will often have a void return type.
using System;
// Declare a delegate type.
delegate void StrMod(ref string str);
class MultiCastDemo {
static void ReplaceSpaces(ref string s) {
Console.WriteLine("Replacing spaces with hyphens.");

s = s.Replace(' ', '-');
}
static void RemoveSpaces(ref string s) {
string temp = "";
int i;
Console.WriteLine("Removing spaces.");
for(i=0; i < s.Length; i++)
if(s[i] != ' ') temp += s[i];
s = temp;
}
static void Reverse(ref string s) {
string temp = "";
int i, j;
Console.WriteLine("Reversing string.");
for(j=0, i=s.Length-1; i >= 0; i--, j++)
temp += s[i];
s = temp;
}
static void Main() {
StrMod strOp;
StrMod replaceSp = ReplaceSpaces;
StrMod removeSp = RemoveSpaces;
StrMod reverseStr = Reverse;
string str = "This is a test";
strOp = replaceSp;
strOp += reverseStr; // Call multicast.
strOp(ref str);
Console.WriteLine("Resulting string: " +
str);
// Remove replace and add remove.
strOp -= replaceSp;
strOp += removeSp;
str = "This is a test."; // reset string
// Call multicast.
strOp(ref str);
Console.WriteLine("Resulting string: " +
str);
Console.WriteLine();
}
}
output
•
•
•
•
•
•

Replacing spaces with hyphens.
Reversing string.
Resulting string: tset-a-si-sihT
Reversing string.
Removing spaces.
Resulting string: .tsetasisihT
Covariance and Contravariance
• here are two features that add flexibility to
delegates: covariance and contravariance.
Normally, the method that you pass to a
delegate must have the same return type
and signature as the delegate.
• However, covariance and contravariance
relax this rule slightly, as it pertains to
derived types.
• Covariance enables a method to be
assigned to a delegate when the
method’s return type is a class derived
from the class specified by the return type
of the delegate.
• Contravariance enables a method to be
assigned to a delegate when a method’s
parameter type is a base class of the
class specified by the delegate’s
declaration.
covariance and contravariance
using System;
class X {
public int Val;
}
// Y is derived from X.
class Y : X { }
// This delegate returns X and takes a Y argument.

delegate X ChangeIt(Y obj);
class CoContraVariance {
static X IncrA(X obj) {
X temp = new X();
temp.Val = obj.Val + 1;
return temp;
}
static Y IncrB(Y obj) {
Y temp = new Y();
temp.Val = obj.Val + 1;
return temp;
}
static void Main() {
Y Yob = new Y();
ChangeIt change = IncrA;
X Xob = change(Yob);
Console.WriteLine("Xob: " + Xob.Val);
change = IncrB;
Yob = (Y) change(Yob);
Console.WriteLine("Yob: " + Yob.Val);
}
}
• ChangeIt change = IncrA;
• uses contravariance to enable IncrA( ) to
be passed to the delegate because IncrA(
) has an X parameter, but the delegate
has a Y parameter. This works
because, with contravariance, if the
parameter type of the method passed to a
delegate is a base class of the parameter
type used by the delegate, then the
method and the delegate are compatible.
• The next line is also legal, but this time it
is because of covariance:
• change = IncrB;
• In this case, the return type of IncrB( )
is Y, but the return type of ChangeIt is
X. However, because the return type of
the method is a class derived from the
return type of the delegate, the two are
compatible.
Anonymous Method

More Related Content

What's hot

Templates2
Templates2Templates2
Templates2
zindadili
 
C# Method overloading
C# Method overloadingC# Method overloading
C# Method overloading
Prem Kumar Badri
 
C++ Template
C++ TemplateC++ Template
C++ Template
Saket Pathak
 
Method overriding
Method overridingMethod overriding
Method overriding
Azaz Maverick
 
Templates in c++
Templates in c++Templates in c++
Templates in c++
Mayank Bhatt
 
Generic Programming
Generic ProgrammingGeneric Programming
Generic Programming
Muhammad Alhalaby
 
Templates
TemplatesTemplates
Templates exception handling
Templates exception handlingTemplates exception handling
Templates exception handling
sanya6900
 
C# Overriding
C# OverridingC# Overriding
C# Overriding
Prem Kumar Badri
 
Template C++ OOP
Template C++ OOPTemplate C++ OOP
Template C++ OOP
Muhammad khan
 
Lecture 5: Functional Programming
Lecture 5: Functional ProgrammingLecture 5: Functional Programming
Lecture 5: Functional ProgrammingEelco Visser
 
Java Concepts
Java ConceptsJava Concepts
Java Concepts
AbdulImrankhan7
 
Object Oriented Programming in PHP
Object Oriented Programming  in PHPObject Oriented Programming  in PHP
Object Oriented Programming in PHP
wahidullah mudaser
 
Implicit conversion and parameters
Implicit conversion and parametersImplicit conversion and parameters
Implicit conversion and parameters
Knoldus Inc.
 
Arrays
ArraysArrays
Arrays
AnaraAlam
 
Method overloading
Method overloadingMethod overloading
Method overloading
Azaz Maverick
 
Pavel kravchenko obj c runtime
Pavel kravchenko obj c runtimePavel kravchenko obj c runtime
Pavel kravchenko obj c runtimeDneprCiklumEvents
 
Computer programming 2 Lesson 11
Computer programming 2  Lesson 11Computer programming 2  Lesson 11
Computer programming 2 Lesson 11
MLG College of Learning, Inc
 

What's hot (20)

Templates2
Templates2Templates2
Templates2
 
C# Method overloading
C# Method overloadingC# Method overloading
C# Method overloading
 
C++ Template
C++ TemplateC++ Template
C++ Template
 
Method overriding
Method overridingMethod overriding
Method overriding
 
Templates in c++
Templates in c++Templates in c++
Templates in c++
 
Generic Programming
Generic ProgrammingGeneric Programming
Generic Programming
 
Templates
TemplatesTemplates
Templates
 
Templates exception handling
Templates exception handlingTemplates exception handling
Templates exception handling
 
C# Overriding
C# OverridingC# Overriding
C# Overriding
 
Template C++ OOP
Template C++ OOPTemplate C++ OOP
Template C++ OOP
 
Lecture 5: Functional Programming
Lecture 5: Functional ProgrammingLecture 5: Functional Programming
Lecture 5: Functional Programming
 
Overloading
OverloadingOverloading
Overloading
 
Java Concepts
Java ConceptsJava Concepts
Java Concepts
 
Object Oriented Programming in PHP
Object Oriented Programming  in PHPObject Oriented Programming  in PHP
Object Oriented Programming in PHP
 
Functional object
Functional objectFunctional object
Functional object
 
Implicit conversion and parameters
Implicit conversion and parametersImplicit conversion and parameters
Implicit conversion and parameters
 
Arrays
ArraysArrays
Arrays
 
Method overloading
Method overloadingMethod overloading
Method overloading
 
Pavel kravchenko obj c runtime
Pavel kravchenko obj c runtimePavel kravchenko obj c runtime
Pavel kravchenko obj c runtime
 
Computer programming 2 Lesson 11
Computer programming 2  Lesson 11Computer programming 2  Lesson 11
Computer programming 2 Lesson 11
 

Similar to Delegate

Visula C# Programming Lecture 6
Visula C# Programming Lecture 6Visula C# Programming Lecture 6
Visula C# Programming Lecture 6
Abou Bakr Ashraf
 
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
 
Java As an OOP Language,Exception Handling & Applets
Java As an OOP Language,Exception Handling & AppletsJava As an OOP Language,Exception Handling & Applets
Java As an OOP Language,Exception Handling & Applets
Helen SagayaRaj
 
Module 4 : methods & parameters
Module 4 : methods & parametersModule 4 : methods & parameters
Module 4 : methods & parameters
Prem Kumar Badri
 
Session 08 - Arrays and Methods
Session 08 - Arrays and MethodsSession 08 - Arrays and Methods
Session 08 - Arrays and Methods
SiddharthSelenium
 
CJP Unit-1 contd.pptx
CJP Unit-1 contd.pptxCJP Unit-1 contd.pptx
CJP Unit-1 contd.pptx
RAJASEKHARV10
 
PROGRAMMING USING C#.NET SARASWATHI RAMALINGAM
PROGRAMMING USING C#.NET SARASWATHI RAMALINGAMPROGRAMMING USING C#.NET SARASWATHI RAMALINGAM
PROGRAMMING USING C#.NET SARASWATHI RAMALINGAM
SaraswathiRamalingam
 
Class 10
Class 10Class 10
Lec 8 03_sept [compatibility mode]
Lec 8 03_sept [compatibility mode]Lec 8 03_sept [compatibility mode]
Lec 8 03_sept [compatibility mode]Palak Sanghani
 
Object and class
Object and classObject and class
Object and class
mohit tripathi
 
C h 04 oop_inheritance
C h 04 oop_inheritanceC h 04 oop_inheritance
C h 04 oop_inheritanceshatha00
 
java tutorial 3
 java tutorial 3 java tutorial 3
java tutorial 3
Tushar Desarda
 
Lecture 4_Java Method-constructor_imp_keywords
Lecture   4_Java Method-constructor_imp_keywordsLecture   4_Java Method-constructor_imp_keywords
Lecture 4_Java Method-constructor_imp_keywords
manish kumar
 
Explain Delegates step by step.
Explain Delegates step by step.Explain Delegates step by step.
Explain Delegates step by step.
Questpond
 
Chapter 6.6
Chapter 6.6Chapter 6.6
Chapter 6.6sotlsoc
 
Inheritance
InheritanceInheritance
Inheritance
Mavoori Soshmitha
 
Java basic tutorial
Java basic tutorialJava basic tutorial
Java basic tutorial
Bui Kiet
 

Similar to Delegate (20)

Visula C# Programming Lecture 6
Visula C# Programming Lecture 6Visula C# Programming Lecture 6
Visula C# Programming Lecture 6
 
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...
 
Lec4
Lec4Lec4
Lec4
 
Java As an OOP Language,Exception Handling & Applets
Java As an OOP Language,Exception Handling & AppletsJava As an OOP Language,Exception Handling & Applets
Java As an OOP Language,Exception Handling & Applets
 
Module 4 : methods & parameters
Module 4 : methods & parametersModule 4 : methods & parameters
Module 4 : methods & parameters
 
Session 08 - Arrays and Methods
Session 08 - Arrays and MethodsSession 08 - Arrays and Methods
Session 08 - Arrays and Methods
 
CJP Unit-1 contd.pptx
CJP Unit-1 contd.pptxCJP Unit-1 contd.pptx
CJP Unit-1 contd.pptx
 
PROGRAMMING USING C#.NET SARASWATHI RAMALINGAM
PROGRAMMING USING C#.NET SARASWATHI RAMALINGAMPROGRAMMING USING C#.NET SARASWATHI RAMALINGAM
PROGRAMMING USING C#.NET SARASWATHI RAMALINGAM
 
Class 10
Class 10Class 10
Class 10
 
Lec 8 03_sept [compatibility mode]
Lec 8 03_sept [compatibility mode]Lec 8 03_sept [compatibility mode]
Lec 8 03_sept [compatibility mode]
 
Object and class
Object and classObject and class
Object and class
 
C h 04 oop_inheritance
C h 04 oop_inheritanceC h 04 oop_inheritance
C h 04 oop_inheritance
 
java tutorial 3
 java tutorial 3 java tutorial 3
java tutorial 3
 
Lecture 4_Java Method-constructor_imp_keywords
Lecture   4_Java Method-constructor_imp_keywordsLecture   4_Java Method-constructor_imp_keywords
Lecture 4_Java Method-constructor_imp_keywords
 
Explain Delegates step by step.
Explain Delegates step by step.Explain Delegates step by step.
Explain Delegates step by step.
 
Chapter 6.6
Chapter 6.6Chapter 6.6
Chapter 6.6
 
Inheritance
InheritanceInheritance
Inheritance
 
Java basic
Java basicJava basic
Java basic
 
Java basic tutorial
Java basic tutorialJava basic tutorial
Java basic tutorial
 
Java Reflection
Java ReflectionJava Reflection
Java Reflection
 

More from abhay singh (15)

Iso 27001
Iso 27001Iso 27001
Iso 27001
 
Web service
Web serviceWeb service
Web service
 
Unsafe
UnsafeUnsafe
Unsafe
 
Threading
ThreadingThreading
Threading
 
Preprocessor
PreprocessorPreprocessor
Preprocessor
 
Networking and socket
Networking and socketNetworking and socket
Networking and socket
 
Namespace
NamespaceNamespace
Namespace
 
Inheritance
InheritanceInheritance
Inheritance
 
Generic
GenericGeneric
Generic
 
Gdi
GdiGdi
Gdi
 
Exception
ExceptionException
Exception
 
Constructor
ConstructorConstructor
Constructor
 
Collection
CollectionCollection
Collection
 
Ado
AdoAdo
Ado
 
Operator overloading
Operator overloadingOperator overloading
Operator overloading
 

Recently uploaded

Unit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdfUnit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdf
Thiyagu K
 
Template Jadual Bertugas Kelas (Boleh Edit)
Template Jadual Bertugas Kelas (Boleh Edit)Template Jadual Bertugas Kelas (Boleh Edit)
Template Jadual Bertugas Kelas (Boleh Edit)
rosedainty
 
Chapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptxChapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptx
Mohd Adib Abd Muin, Senior Lecturer at Universiti Utara Malaysia
 
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup   New Member Orientation and Q&A (May 2024).pdfWelcome to TechSoup   New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
TechSoup
 
The approach at University of Liverpool.pptx
The approach at University of Liverpool.pptxThe approach at University of Liverpool.pptx
The approach at University of Liverpool.pptx
Jisc
 
ESC Beyond Borders _From EU to You_ InfoPack general.pdf
ESC Beyond Borders _From EU to You_ InfoPack general.pdfESC Beyond Borders _From EU to You_ InfoPack general.pdf
ESC Beyond Borders _From EU to You_ InfoPack general.pdf
Fundacja Rozwoju Społeczeństwa Przedsiębiorczego
 
The French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free downloadThe French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free download
Vivekanand Anglo Vedic Academy
 
How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17
Celine George
 
Language Across the Curriculm LAC B.Ed.
Language Across the  Curriculm LAC B.Ed.Language Across the  Curriculm LAC B.Ed.
Language Across the Curriculm LAC B.Ed.
Atul Kumar Singh
 
Basic phrases for greeting and assisting costumers
Basic phrases for greeting and assisting costumersBasic phrases for greeting and assisting costumers
Basic phrases for greeting and assisting costumers
PedroFerreira53928
 
2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...
Sandy Millin
 
The Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdfThe Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdf
kaushalkr1407
 
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCECLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
BhavyaRajput3
 
Sectors of the Indian Economy - Class 10 Study Notes pdf
Sectors of the Indian Economy - Class 10 Study Notes pdfSectors of the Indian Economy - Class 10 Study Notes pdf
Sectors of the Indian Economy - Class 10 Study Notes pdf
Vivekanand Anglo Vedic Academy
 
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptxStudents, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
EduSkills OECD
 
How to Break the cycle of negative Thoughts
How to Break the cycle of negative ThoughtsHow to Break the cycle of negative Thoughts
How to Break the cycle of negative Thoughts
Col Mukteshwar Prasad
 
Additional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdfAdditional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdf
joachimlavalley1
 
How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
Jisc
 
How to Split Bills in the Odoo 17 POS Module
How to Split Bills in the Odoo 17 POS ModuleHow to Split Bills in the Odoo 17 POS Module
How to Split Bills in the Odoo 17 POS Module
Celine George
 
The Art Pastor's Guide to Sabbath | Steve Thomason
The Art Pastor's Guide to Sabbath | Steve ThomasonThe Art Pastor's Guide to Sabbath | Steve Thomason
The Art Pastor's Guide to Sabbath | Steve Thomason
Steve Thomason
 

Recently uploaded (20)

Unit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdfUnit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdf
 
Template Jadual Bertugas Kelas (Boleh Edit)
Template Jadual Bertugas Kelas (Boleh Edit)Template Jadual Bertugas Kelas (Boleh Edit)
Template Jadual Bertugas Kelas (Boleh Edit)
 
Chapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptxChapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptx
 
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup   New Member Orientation and Q&A (May 2024).pdfWelcome to TechSoup   New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
 
The approach at University of Liverpool.pptx
The approach at University of Liverpool.pptxThe approach at University of Liverpool.pptx
The approach at University of Liverpool.pptx
 
ESC Beyond Borders _From EU to You_ InfoPack general.pdf
ESC Beyond Borders _From EU to You_ InfoPack general.pdfESC Beyond Borders _From EU to You_ InfoPack general.pdf
ESC Beyond Borders _From EU to You_ InfoPack general.pdf
 
The French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free downloadThe French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free download
 
How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17
 
Language Across the Curriculm LAC B.Ed.
Language Across the  Curriculm LAC B.Ed.Language Across the  Curriculm LAC B.Ed.
Language Across the Curriculm LAC B.Ed.
 
Basic phrases for greeting and assisting costumers
Basic phrases for greeting and assisting costumersBasic phrases for greeting and assisting costumers
Basic phrases for greeting and assisting costumers
 
2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...
 
The Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdfThe Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdf
 
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCECLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
 
Sectors of the Indian Economy - Class 10 Study Notes pdf
Sectors of the Indian Economy - Class 10 Study Notes pdfSectors of the Indian Economy - Class 10 Study Notes pdf
Sectors of the Indian Economy - Class 10 Study Notes pdf
 
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptxStudents, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
 
How to Break the cycle of negative Thoughts
How to Break the cycle of negative ThoughtsHow to Break the cycle of negative Thoughts
How to Break the cycle of negative Thoughts
 
Additional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdfAdditional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdf
 
How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
 
How to Split Bills in the Odoo 17 POS Module
How to Split Bills in the Odoo 17 POS ModuleHow to Split Bills in the Odoo 17 POS Module
How to Split Bills in the Odoo 17 POS Module
 
The Art Pastor's Guide to Sabbath | Steve Thomason
The Art Pastor's Guide to Sabbath | Steve ThomasonThe Art Pastor's Guide to Sabbath | Steve Thomason
The Art Pastor's Guide to Sabbath | Steve Thomason
 

Delegate

  • 2. Delegate • A delegate provides a way to encapsulate a method. • An event is a notification that some action has occurred. • Delegates and events are related because an event is built upon a delegate.
  • 3. • A delegate is an object that can refer to a method. • when you create a delegate, you are creating an object that can hold a reference to a method. • Furthermore, the method can be called through this reference. • A delegate can invoke the method to which it refers. • A delegate in C# is similar to a function pointer in C/C++.
  • 4. • A delegate type is declared using the keyword delegate. delegate return-type name (parameter-list ); • return-type is the type of value returned by the methods that the delegate will be calling. • The name of the delegate is specified by name. • The parameters required by the methods called through the delegate are specified in the parameter-list.
  • 5. • A delegate instance (Object) can refer to and call methods whose return type and parameter list match those specified by the delegate declaration. • The method can be either an instance method associated with an object or a static method associated with a class.
  • 6. using System; delegate string StrMod(string str); class DelegateTest { static string ReplaceSpaces(string s) { Console.WriteLine("Replacing spaces with hyphens."); return s.Replace(' ', '-'); }
  • 7. static string RemoveSpaces(string s) { string temp = ""; int i; Console.WriteLine("Removing spaces.") for(i=0; i < s.Length; i++) if(s[i] != ' ') temp += s[i]; return temp; }
  • 8. static string Reverse(string s) { string temp = ""; int i, j; Console.WriteLine("Reversing string."); for(j=0, i=s.Length-1; i >= 0; i--, j++) temp += s[i]; return temp; }
  • 9. static void Main() { StrMod strOp = new StrMod(ReplaceSpaces); string str; str = strOp("This is a test."); Console.WriteLine("Resulting string: " + str); Console.WriteLine(); strOp2 = new StrMod(RemoveSpaces); str = strOp2("This is a test."); Console.WriteLine("Resulting string: " + str);
  • 10. strOp = new StrMod(Reverse); str = strOp("This is a test."); Console.WriteLine("Resulting string: " + str); } } //output Replacing spaces with hyphens. Resulting string: This-is-a-test. Removing spaces. Resulting string: Thisisatest. Reversing string. Resulting string: .tset a si sihT
  • 11.
  • 12. Delegate Method Group Conversion • Since version 2.0, C# has included an option that significantly simplifies the syntax that assigns a method to a delegate. • This feature is called method group conversion, and it allows you to simply assign the name of a method to a delegate, without using new or explicitly invoking the delegate’s constructor.
  • 13. // use method group conversion StrMod strOp = ReplaceSpaces; string str; // Call methods through the delegate. str = strOp("This is a test."); Console.WriteLine("Resulting string: " + str); Console.WriteLine();
  • 14.
  • 15. Instance Methods as Delegates delegate string StrMod(string str); class StringOps { public string ReplaceSpaces(string s) { Console.WriteLine("Replacing spaces with hyphens."); return s.Replace(' ', '-'); }
  • 16. public string RemoveSpaces(string s) { string temp = ""; int i; Console.WriteLine("Removing spaces."); for(i=0; i < s.Length; i++) if(s[i] != ' ') temp += s[i]; return temp; }
  • 17. public string Reverse(string s) { string temp = ""; int i, j; Console.WriteLine("Reversing string."); for(j=0, i=s.Length-1; i >= 0; i--, j++) temp += s[i]; return temp; } } class DelegateTest { static void Main() { StringOps so = new StringOps();
  • 18. // Initialize a delegate. StrMod strOp = so.ReplaceSpaces; string str; // Call methods through delegates. str = strOp("This is a test."); Console.WriteLine("Resulting string: " + str); Console.WriteLine();
  • 19. strOp = so.RemoveSpaces; str = strOp("This is a test."); Console.WriteLine("Resulting string: " + str); Console.WriteLine(); strOp = so.Reverse; str = strOp("This is a test."); Console.WriteLine("Resulting string: " + str); }}
  • 20.
  • 21. Multicasting • One of the most exciting features of a delegate is its support for multicasting. • Multicasting is the ability to create an invocation list, or chain, of methods that will be automatically called when a delegate is invoked. • Such a chain is very easy to create.
  • 22. • Simply instantiate a delegate, and then use the + or += operator to add methods to the chain. • To remove a method, use – or – =. • If the delegate returns a value, then the value returned by the last method in the list becomes the return value of the entire delegate invocation. • Thus, a delegate that makes use of multicasting will often have a void return type.
  • 23. using System; // Declare a delegate type. delegate void StrMod(ref string str); class MultiCastDemo { static void ReplaceSpaces(ref string s) { Console.WriteLine("Replacing spaces with hyphens."); s = s.Replace(' ', '-'); }
  • 24. static void RemoveSpaces(ref string s) { string temp = ""; int i; Console.WriteLine("Removing spaces."); for(i=0; i < s.Length; i++) if(s[i] != ' ') temp += s[i]; s = temp; }
  • 25. static void Reverse(ref string s) { string temp = ""; int i, j; Console.WriteLine("Reversing string."); for(j=0, i=s.Length-1; i >= 0; i--, j++) temp += s[i]; s = temp; }
  • 26. static void Main() { StrMod strOp; StrMod replaceSp = ReplaceSpaces; StrMod removeSp = RemoveSpaces; StrMod reverseStr = Reverse; string str = "This is a test"; strOp = replaceSp; strOp += reverseStr; // Call multicast. strOp(ref str); Console.WriteLine("Resulting string: " + str);
  • 27. // Remove replace and add remove. strOp -= replaceSp; strOp += removeSp; str = "This is a test."; // reset string // Call multicast. strOp(ref str); Console.WriteLine("Resulting string: " + str); Console.WriteLine(); } }
  • 28. output • • • • • • Replacing spaces with hyphens. Reversing string. Resulting string: tset-a-si-sihT Reversing string. Removing spaces. Resulting string: .tsetasisihT
  • 29.
  • 30. Covariance and Contravariance • here are two features that add flexibility to delegates: covariance and contravariance. Normally, the method that you pass to a delegate must have the same return type and signature as the delegate. • However, covariance and contravariance relax this rule slightly, as it pertains to derived types.
  • 31. • Covariance enables a method to be assigned to a delegate when the method’s return type is a class derived from the class specified by the return type of the delegate. • Contravariance enables a method to be assigned to a delegate when a method’s parameter type is a base class of the class specified by the delegate’s declaration.
  • 32. covariance and contravariance using System; class X { public int Val; } // Y is derived from X. class Y : X { } // This delegate returns X and takes a Y argument. delegate X ChangeIt(Y obj);
  • 33. class CoContraVariance { static X IncrA(X obj) { X temp = new X(); temp.Val = obj.Val + 1; return temp; } static Y IncrB(Y obj) { Y temp = new Y(); temp.Val = obj.Val + 1; return temp; }
  • 34. static void Main() { Y Yob = new Y(); ChangeIt change = IncrA; X Xob = change(Yob); Console.WriteLine("Xob: " + Xob.Val); change = IncrB; Yob = (Y) change(Yob); Console.WriteLine("Yob: " + Yob.Val); } }
  • 35. • ChangeIt change = IncrA; • uses contravariance to enable IncrA( ) to be passed to the delegate because IncrA( ) has an X parameter, but the delegate has a Y parameter. This works because, with contravariance, if the parameter type of the method passed to a delegate is a base class of the parameter type used by the delegate, then the method and the delegate are compatible.
  • 36. • The next line is also legal, but this time it is because of covariance: • change = IncrB; • In this case, the return type of IncrB( ) is Y, but the return type of ChangeIt is X. However, because the return type of the method is a class derived from the return type of the delegate, the two are compatible.