SlideShare a Scribd company logo
1 of 24
Operators, Delegates, and
Events
Overview
 Introduction to Operators
 Operator Overloading
 Creating and Using Delegates
 Defining and Using Events
Introduction to Operators
 Operators and Methods
 Predefined C# Operators
Operators and Methods
 Using methods
 Reduces clarity
 Increases risk of errors, both syntactic and semantic
 Using operators
 Makes expressions clear
myIntVar1 = Int.Add(myIntVar2,
Int.Add(Int.Add(myIntVar3,
myIntVar4), 33));
myIntVar1 = myIntVar2 + myIntVar3 + myIntVar4 + 33;
Predefined C# Operators
Operator Categories
Arithmetic Member access
Logical (Boolean
and bitwise)
Indexing
String concatenation Cast
Increment and decrement Conditional
Shift Delegate concatenation and
removal
Relational Object creation
Assignment Type information
Overflow exception control Indirection and address
Operator Overloading
 Introduction to Operator Overloading
 Overloading Relational Operators
 Overloading Logical Operators
 Overloading Conversion Operators
 Overloading Operators Multiple Times
 Quiz: Spot the Bugs
Introduction to Operator
Overloading
 Operator overloading
 Define your own operators only when appropriate
 Operator syntax
 Operatorop, where op is the operator being overloaded
 Example
public static Time operator+(Time t1, Time t2)
{
int newHours = t1.hours + t2.hours;
int newMinutes = t1.minutes + t2.minutes;
return new Time(newHours, newMinutes);
}
Overloading Relational Operators
 Relational operators must be paired
 < and >
 <= and >=
 == and !=
 Override the Equals method if overloading == and !=
 Override the GetHashCode method if overriding equals
method
Overloading Logical Operators
 Operators && and || cannot be overloaded directly
 They are evaluated in terms of &, |, true, and false, which
can be overloaded
 x && y is evaluated as T.false(x) ? x : T.&(x, y)
 x || y is evaluated as T.true(x) ? x : T.|(x, y)
Overloading Conversion
Operators
 Overloaded conversion operators
 If a class defines a string conversion operator
 The class should override ToString
public static explicit operator Time (float hours)
{ ... }
public static explicit operator float (Time t1)
{ ... }
public static implicit operator string (Time t1)
{ ... }
Overloading Operators Multiple
Times
 The same operator can be overloaded multiple times
public static Time operator+(Time t1, int hours)
{...}
public static Time operator+(Time t1, float hours)
{...}
public static Time operator-(Time t1, int hours)
{...}
public static Time operator-(Time t1, float hours)
{...}
Creating and Using Delegates
 Scenario: Power Station
 Analyzing the Problem
 Creating Delegates
 Using Delegates
Scenario: Power Station
 The problem
 How to respond to temperature events in a power station
 Specifically, if the temperature of the reactor core rises
above a certain temperature, coolant pumps need to be
alerted and switched on
 Possible solutions
 Should all coolant pumps monitor the core temperature?
 Should a component that monitors the core turn on the
appropriate pumps when the temperature changes?
Analyzing the Problem
 Existing concerns
 There may be several types of pumps, supplied by different
manufacturers
 Each pump could have its own method for activation
 Future concerns
 To add a new pump, the entire code will need to change
 A high overhead cost will result with every such addition
 A solution
 Use delegates in your code
Creating Delegates
 A delegate allows a method to be called indirectly
 It contains a reference to a method
 All methods invoked by the same delegate must have the
same parameters and return value
MethodX
delegate ?
Method1()
{
...
}
Method2()
{
...
}
DoWork()
{
...
MethodX();
...
}
Using Delegates
 To call a delegate, use method syntax
public delegate void StartPumpCallback( );
...
StartPumpCallback callback;
...
callback = new
StartPumpCallback(ed1.StartElectricPumpRunning);
...
callback( );
No Method Body
Call Here
No Call Here
Anonymous Methods
 If we need to pass methods as function parameters we
need to use delegates in C#. E.g Events, Callbacks,
Threading.
 A delegate with an inline code block
Lambda Expression
 Lambda expressions are a way to write anonymous methods with a
more functional syntax.
 “=>” Read as “goes into”.
 e.g x => x + 2 Read as “x goes into x + 2”.
Multicast Delegates
 A delegate which points to more than one function at a
time.
 For making a multicast delegate use +=.
 For removing a function from the list use -=
public delegate void StartPumpCallback( );
...
StartPumpCallback callback;
callback = new
StartPumpCallback(ed1.StartElectricPumpRunning);
callback += new
StartPumpCallback(sd1.StartElectricPumpRunning);
callback( );
Defining and Using Events
 How Events Work
 Defining Events
 Passing Event Parameters
 Demonstration: Handling Events
How Events Work
 Publisher
 Raises an event to alert all interested objects (subscribers)
 Subscriber
 Provides a method to be called when the event is raised
Defining Events
 Defining an event
 Subscribing to an event
 Notifying subscribers to an event
public delegate void StartPumpCallback( );
private event StartPumpCallback CoreOverheating;
PneumaticPumpDriver pd1 = new PneumaticPumpDriver( );
...
CoreOverheating += new StartPumpCallback(pd1.SwitchOn);
public void SwitchOnAllPumps( ) {
if (CoreOverheating != null) {
CoreOverheating( );
}
}
Passing Event Parameters
 Parameters for events should be passed as EventArgs
 Define a class descended from EventArgs to act as a
container for event parameters
 The same subscribing method may be called by several
events
 Always pass the event publisher (sender) as the first
parameter to the method
Review
 Introduction to Operators
 Operator Overloading
 Creating and Using Delegates
 Defining and Using Events

More Related Content

What's hot

Operator Overloading
Operator OverloadingOperator Overloading
Operator OverloadingNilesh Dalvi
 
Evolution of C# delegates
Evolution of C# delegatesEvolution of C# delegates
Evolution of C# delegatesmbaric
 
Chapter 8 - Exceptions and Assertions Edit summary
Chapter 8 - Exceptions and Assertions  Edit summaryChapter 8 - Exceptions and Assertions  Edit summary
Chapter 8 - Exceptions and Assertions Edit summaryEduardo Bergavera
 
Pattern Matching - at a glance
Pattern Matching - at a glancePattern Matching - at a glance
Pattern Matching - at a glanceKnoldus Inc.
 
Advanced Javascript
Advanced JavascriptAdvanced Javascript
Advanced Javascriptrelay12
 
Explain Delegates step by step.
Explain Delegates step by step.Explain Delegates step by step.
Explain Delegates step by step.Questpond
 
04. constructor & destructor
04. constructor & destructor04. constructor & destructor
04. constructor & destructorHaresh Jaiswal
 
Constructor and Destructor
Constructor and DestructorConstructor and Destructor
Constructor and DestructorKamal Acharya
 
Presentation 1st
Presentation 1stPresentation 1st
Presentation 1stConnex
 
08 c++ Operator Overloading.ppt
08 c++ Operator Overloading.ppt08 c++ Operator Overloading.ppt
08 c++ Operator Overloading.pptTareq Hasan
 
Presentation 3rd
Presentation 3rdPresentation 3rd
Presentation 3rdConnex
 

What's hot (20)

Constructor in java
Constructor in javaConstructor in java
Constructor in java
 
Operator Overloading
Operator OverloadingOperator Overloading
Operator Overloading
 
C# Delegates
C# DelegatesC# Delegates
C# Delegates
 
Evolution of C# delegates
Evolution of C# delegatesEvolution of C# delegates
Evolution of C# delegates
 
Chapter 8 - Exceptions and Assertions Edit summary
Chapter 8 - Exceptions and Assertions  Edit summaryChapter 8 - Exceptions and Assertions  Edit summary
Chapter 8 - Exceptions and Assertions Edit summary
 
Introduction to C++
Introduction to C++Introduction to C++
Introduction to C++
 
Pattern Matching - at a glance
Pattern Matching - at a glancePattern Matching - at a glance
Pattern Matching - at a glance
 
Unit ii
Unit   iiUnit   ii
Unit ii
 
Advanced Javascript
Advanced JavascriptAdvanced Javascript
Advanced Javascript
 
Delegates and events
Delegates and events   Delegates and events
Delegates and events
 
Intake 38 3
Intake 38 3Intake 38 3
Intake 38 3
 
Explain Delegates step by step.
Explain Delegates step by step.Explain Delegates step by step.
Explain Delegates step by step.
 
04. constructor & destructor
04. constructor & destructor04. constructor & destructor
04. constructor & destructor
 
Constructor and Destructor
Constructor and DestructorConstructor and Destructor
Constructor and Destructor
 
Presentation 1st
Presentation 1stPresentation 1st
Presentation 1st
 
Delegates in C#
Delegates in C#Delegates in C#
Delegates in C#
 
Actionscript
ActionscriptActionscript
Actionscript
 
08 c++ Operator Overloading.ppt
08 c++ Operator Overloading.ppt08 c++ Operator Overloading.ppt
08 c++ Operator Overloading.ppt
 
Presentation 3rd
Presentation 3rdPresentation 3rd
Presentation 3rd
 
Delegates and events in C#
Delegates and events in C#Delegates and events in C#
Delegates and events in C#
 

Similar to Module 13 operators, delegates, and events

Lec 28 - operator overloading
Lec 28 - operator overloadingLec 28 - operator overloading
Lec 28 - operator overloadingPrincess Sam
 
UNIT III.ppt
UNIT III.pptUNIT III.ppt
UNIT III.pptAjit Mali
 
overloading in C++
overloading in C++overloading in C++
overloading in C++Prof Ansari
 
Whats New In C# 4 0 - NetPonto
Whats New In C# 4 0 - NetPontoWhats New In C# 4 0 - NetPonto
Whats New In C# 4 0 - NetPontoPaulo Morgado
 
Generalized Functors - Realizing Command Design Pattern in C++
Generalized Functors - Realizing Command Design Pattern in C++Generalized Functors - Realizing Command Design Pattern in C++
Generalized Functors - Realizing Command Design Pattern in C++ppd1961
 
Csharp4 delegates lambda_and_events
Csharp4 delegates lambda_and_eventsCsharp4 delegates lambda_and_events
Csharp4 delegates lambda_and_eventsAbed Bukhari
 
Lec 26.27-operator overloading
Lec 26.27-operator overloadingLec 26.27-operator overloading
Lec 26.27-operator overloadingPrincess Sam
 
Object oriented programming system with C++
Object oriented programming system with C++Object oriented programming system with C++
Object oriented programming system with C++msharshitha03s
 
Java fundamentals
Java fundamentalsJava fundamentals
Java fundamentalsHCMUTE
 

Similar to Module 13 operators, delegates, and events (20)

Operator overloading
Operator overloadingOperator overloading
Operator overloading
 
3d7b7 session4 c++
3d7b7 session4 c++3d7b7 session4 c++
3d7b7 session4 c++
 
Lec 28 - operator overloading
Lec 28 - operator overloadingLec 28 - operator overloading
Lec 28 - operator overloading
 
Unit iii
Unit iiiUnit iii
Unit iii
 
Rx workshop
Rx workshopRx workshop
Rx workshop
 
UNIT III.ppt
UNIT III.pptUNIT III.ppt
UNIT III.ppt
 
UNIT III (2).ppt
UNIT III (2).pptUNIT III (2).ppt
UNIT III (2).ppt
 
overloading in C++
overloading in C++overloading in C++
overloading in C++
 
Whats New In C# 4 0 - NetPonto
Whats New In C# 4 0 - NetPontoWhats New In C# 4 0 - NetPonto
Whats New In C# 4 0 - NetPonto
 
Generalized Functors - Realizing Command Design Pattern in C++
Generalized Functors - Realizing Command Design Pattern in C++Generalized Functors - Realizing Command Design Pattern in C++
Generalized Functors - Realizing Command Design Pattern in C++
 
Object Oriented Programming with C++
Object Oriented Programming with C++Object Oriented Programming with C++
Object Oriented Programming with C++
 
Csharp4 delegates lambda_and_events
Csharp4 delegates lambda_and_eventsCsharp4 delegates lambda_and_events
Csharp4 delegates lambda_and_events
 
Operator overloading
Operator overloadingOperator overloading
Operator overloading
 
Lec 26.27-operator overloading
Lec 26.27-operator overloadingLec 26.27-operator overloading
Lec 26.27-operator overloading
 
Chap 5 c++
Chap 5 c++Chap 5 c++
Chap 5 c++
 
Object oriented programming system with C++
Object oriented programming system with C++Object oriented programming system with C++
Object oriented programming system with C++
 
Overloading
OverloadingOverloading
Overloading
 
Apclass (2)
Apclass (2)Apclass (2)
Apclass (2)
 
Java fundamentals
Java fundamentalsJava fundamentals
Java fundamentals
 
C++.pptx
C++.pptxC++.pptx
C++.pptx
 

More from Prem Kumar Badri

Module 14 properties and indexers
Module 14 properties and indexersModule 14 properties and indexers
Module 14 properties and indexersPrem Kumar Badri
 
Module 10 : creating and destroying objects
Module 10 : creating and destroying objectsModule 10 : creating and destroying objects
Module 10 : creating and destroying objectsPrem Kumar Badri
 
Module 9 : using reference type variables
Module 9 : using reference type variablesModule 9 : using reference type variables
Module 9 : using reference type variablesPrem Kumar Badri
 
Module 8 : Implementing collections and generics
Module 8 : Implementing collections and genericsModule 8 : Implementing collections and generics
Module 8 : Implementing collections and genericsPrem Kumar Badri
 
Module 6 : Essentials of Object Oriented Programming
Module 6 : Essentials of Object Oriented ProgrammingModule 6 : Essentials of Object Oriented Programming
Module 6 : Essentials of Object Oriented ProgrammingPrem Kumar Badri
 
Module 5 : Statements & Exceptions
Module 5 : Statements & ExceptionsModule 5 : Statements & Exceptions
Module 5 : Statements & ExceptionsPrem Kumar Badri
 
Module 4 : methods & parameters
Module 4 : methods & parametersModule 4 : methods & parameters
Module 4 : methods & parametersPrem Kumar Badri
 
Module 3 : using value type variables
Module 3 : using value type variablesModule 3 : using value type variables
Module 3 : using value type variablesPrem Kumar Badri
 
Module 1 : Overview of the Microsoft .NET Platform
Module 1 : Overview of the Microsoft .NET PlatformModule 1 : Overview of the Microsoft .NET Platform
Module 1 : Overview of the Microsoft .NET PlatformPrem Kumar Badri
 
C# Non generics collection
C# Non generics collectionC# Non generics collection
C# Non generics collectionPrem Kumar Badri
 
C# Filtering in generic collections
C# Filtering in generic collectionsC# Filtering in generic collections
C# Filtering in generic collectionsPrem Kumar Badri
 

More from Prem Kumar Badri (20)

Module 14 properties and indexers
Module 14 properties and indexersModule 14 properties and indexers
Module 14 properties and indexers
 
Module 11 : Inheritance
Module 11 : InheritanceModule 11 : Inheritance
Module 11 : Inheritance
 
Module 10 : creating and destroying objects
Module 10 : creating and destroying objectsModule 10 : creating and destroying objects
Module 10 : creating and destroying objects
 
Module 9 : using reference type variables
Module 9 : using reference type variablesModule 9 : using reference type variables
Module 9 : using reference type variables
 
Module 8 : Implementing collections and generics
Module 8 : Implementing collections and genericsModule 8 : Implementing collections and generics
Module 8 : Implementing collections and generics
 
Module 7 : Arrays
Module 7 : ArraysModule 7 : Arrays
Module 7 : Arrays
 
Module 6 : Essentials of Object Oriented Programming
Module 6 : Essentials of Object Oriented ProgrammingModule 6 : Essentials of Object Oriented Programming
Module 6 : Essentials of Object Oriented Programming
 
Module 5 : Statements & Exceptions
Module 5 : Statements & ExceptionsModule 5 : Statements & Exceptions
Module 5 : Statements & Exceptions
 
Module 4 : methods & parameters
Module 4 : methods & parametersModule 4 : methods & parameters
Module 4 : methods & parameters
 
Module 3 : using value type variables
Module 3 : using value type variablesModule 3 : using value type variables
Module 3 : using value type variables
 
Module 2: Overview of c#
Module 2:  Overview of c#Module 2:  Overview of c#
Module 2: Overview of c#
 
Module 1 : Overview of the Microsoft .NET Platform
Module 1 : Overview of the Microsoft .NET PlatformModule 1 : Overview of the Microsoft .NET Platform
Module 1 : Overview of the Microsoft .NET Platform
 
C# Non generics collection
C# Non generics collectionC# Non generics collection
C# Non generics collection
 
C# Multi threading
C# Multi threadingC# Multi threading
C# Multi threading
 
C# Method overloading
C# Method overloadingC# Method overloading
C# Method overloading
 
C# Inheritance
C# InheritanceC# Inheritance
C# Inheritance
 
C# Generic collections
C# Generic collectionsC# Generic collections
C# Generic collections
 
C# Global Assembly Cache
C# Global Assembly CacheC# Global Assembly Cache
C# Global Assembly Cache
 
C# Filtering in generic collections
C# Filtering in generic collectionsC# Filtering in generic collections
C# Filtering in generic collections
 
C# File IO Operations
C# File IO OperationsC# File IO Operations
C# File IO Operations
 

Recently uploaded

Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for BeginnersSabitha Banu
 
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
 
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
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
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
 
भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,Virag Sontakke
 
CELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxCELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxJiesonDelaCerna
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceSamikshaHamane
 
Meghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentMeghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentInMediaRes1
 
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
 
Capitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptxCapitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptxCapitolTechU
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon AUnboundStockton
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfSumit Tiwari
 
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfFraming an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfUjwalaBharambe
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...jaredbarbolino94
 
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
 

Recently uploaded (20)

Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for Beginners
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
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
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.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
 
भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,
 
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
 
CELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxCELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptx
 
9953330565 Low Rate Call Girls In Rohini Delhi NCR
9953330565 Low Rate Call Girls In Rohini  Delhi NCR9953330565 Low Rate Call Girls In Rohini  Delhi NCR
9953330565 Low Rate Call Girls In Rohini Delhi NCR
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in Pharmacovigilance
 
Meghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentMeghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media Component
 
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
 
Capitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptxCapitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptx
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
 
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfFraming an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...
 
Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...
 
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
 

Module 13 operators, delegates, and events

  • 2. Overview  Introduction to Operators  Operator Overloading  Creating and Using Delegates  Defining and Using Events
  • 3. Introduction to Operators  Operators and Methods  Predefined C# Operators
  • 4. Operators and Methods  Using methods  Reduces clarity  Increases risk of errors, both syntactic and semantic  Using operators  Makes expressions clear myIntVar1 = Int.Add(myIntVar2, Int.Add(Int.Add(myIntVar3, myIntVar4), 33)); myIntVar1 = myIntVar2 + myIntVar3 + myIntVar4 + 33;
  • 5. Predefined C# Operators Operator Categories Arithmetic Member access Logical (Boolean and bitwise) Indexing String concatenation Cast Increment and decrement Conditional Shift Delegate concatenation and removal Relational Object creation Assignment Type information Overflow exception control Indirection and address
  • 6. Operator Overloading  Introduction to Operator Overloading  Overloading Relational Operators  Overloading Logical Operators  Overloading Conversion Operators  Overloading Operators Multiple Times  Quiz: Spot the Bugs
  • 7. Introduction to Operator Overloading  Operator overloading  Define your own operators only when appropriate  Operator syntax  Operatorop, where op is the operator being overloaded  Example public static Time operator+(Time t1, Time t2) { int newHours = t1.hours + t2.hours; int newMinutes = t1.minutes + t2.minutes; return new Time(newHours, newMinutes); }
  • 8. Overloading Relational Operators  Relational operators must be paired  < and >  <= and >=  == and !=  Override the Equals method if overloading == and !=  Override the GetHashCode method if overriding equals method
  • 9. Overloading Logical Operators  Operators && and || cannot be overloaded directly  They are evaluated in terms of &, |, true, and false, which can be overloaded  x && y is evaluated as T.false(x) ? x : T.&(x, y)  x || y is evaluated as T.true(x) ? x : T.|(x, y)
  • 10. Overloading Conversion Operators  Overloaded conversion operators  If a class defines a string conversion operator  The class should override ToString public static explicit operator Time (float hours) { ... } public static explicit operator float (Time t1) { ... } public static implicit operator string (Time t1) { ... }
  • 11. Overloading Operators Multiple Times  The same operator can be overloaded multiple times public static Time operator+(Time t1, int hours) {...} public static Time operator+(Time t1, float hours) {...} public static Time operator-(Time t1, int hours) {...} public static Time operator-(Time t1, float hours) {...}
  • 12. Creating and Using Delegates  Scenario: Power Station  Analyzing the Problem  Creating Delegates  Using Delegates
  • 13. Scenario: Power Station  The problem  How to respond to temperature events in a power station  Specifically, if the temperature of the reactor core rises above a certain temperature, coolant pumps need to be alerted and switched on  Possible solutions  Should all coolant pumps monitor the core temperature?  Should a component that monitors the core turn on the appropriate pumps when the temperature changes?
  • 14. Analyzing the Problem  Existing concerns  There may be several types of pumps, supplied by different manufacturers  Each pump could have its own method for activation  Future concerns  To add a new pump, the entire code will need to change  A high overhead cost will result with every such addition  A solution  Use delegates in your code
  • 15. Creating Delegates  A delegate allows a method to be called indirectly  It contains a reference to a method  All methods invoked by the same delegate must have the same parameters and return value MethodX delegate ? Method1() { ... } Method2() { ... } DoWork() { ... MethodX(); ... }
  • 16. Using Delegates  To call a delegate, use method syntax public delegate void StartPumpCallback( ); ... StartPumpCallback callback; ... callback = new StartPumpCallback(ed1.StartElectricPumpRunning); ... callback( ); No Method Body Call Here No Call Here
  • 17. Anonymous Methods  If we need to pass methods as function parameters we need to use delegates in C#. E.g Events, Callbacks, Threading.  A delegate with an inline code block
  • 18. Lambda Expression  Lambda expressions are a way to write anonymous methods with a more functional syntax.  “=>” Read as “goes into”.  e.g x => x + 2 Read as “x goes into x + 2”.
  • 19. Multicast Delegates  A delegate which points to more than one function at a time.  For making a multicast delegate use +=.  For removing a function from the list use -= public delegate void StartPumpCallback( ); ... StartPumpCallback callback; callback = new StartPumpCallback(ed1.StartElectricPumpRunning); callback += new StartPumpCallback(sd1.StartElectricPumpRunning); callback( );
  • 20. Defining and Using Events  How Events Work  Defining Events  Passing Event Parameters  Demonstration: Handling Events
  • 21. How Events Work  Publisher  Raises an event to alert all interested objects (subscribers)  Subscriber  Provides a method to be called when the event is raised
  • 22. Defining Events  Defining an event  Subscribing to an event  Notifying subscribers to an event public delegate void StartPumpCallback( ); private event StartPumpCallback CoreOverheating; PneumaticPumpDriver pd1 = new PneumaticPumpDriver( ); ... CoreOverheating += new StartPumpCallback(pd1.SwitchOn); public void SwitchOnAllPumps( ) { if (CoreOverheating != null) { CoreOverheating( ); } }
  • 23. Passing Event Parameters  Parameters for events should be passed as EventArgs  Define a class descended from EventArgs to act as a container for event parameters  The same subscribing method may be called by several events  Always pass the event publisher (sender) as the first parameter to the method
  • 24. Review  Introduction to Operators  Operator Overloading  Creating and Using Delegates  Defining and Using Events