Module 12: Operators, Delegates, and Events. Overview Introduction to Operators Operator Overloading Creating and Using Delegates Defining and Using Events.

Slides:



Advertisements
Similar presentations
AP Computer Science Anthony Keen. Computer 101 What happens when you turn a computer on? –BIOS tries to start a system loader –A system loader tries to.
Advertisements

Module 4: Statements and Exceptions. Overview Introduction to Statements Using Selection Statements Using Iteration Statements Using Jump Statements Handling.
Basic -2 Classes and Objects. Classes and Objects A class is a complex data TYPE An object is an instance of a class. Example: Class: Person Objects:
Language Fundamentals in brief C# - Introduction.
Chapter 7 User-Defined Methods. Chapter Objectives  Understand how methods are used in Java programming  Learn about standard (predefined) methods and.
CS2200 Software Development Lecture: Object class A. O’Riordan, 2008.
Some basic I/O.
C# vs. C++ What's Different & What's New. An example C# public sometype myfn { get; set; } C++ public: sometype myfn { sometype get (); void set (sometype.
1 Operator Overloading in C++ Copyright Kip Irvine, All rights reserved. Only students enrolled in COP 4338 at Florida International University may.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 14: Pointers, Classes, Virtual Functions, and Abstract Classes.
FEN 2012 UCN Technology: Computer Science1 C# - Introduction Language Fundamentals in Brief.
Programming Language C++ Xulong Peng CSC415 Programming Languages.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
Module 3: Working with Components. Overview An Introduction to Key.NET Framework Development Technologies Creating a Simple.NET Framework Component Creating.
1 Advanced Programming IF. 2 Control Structures Program of control –Program performs one statement then goes to next line Sequential execution –Different.
C#.Net Development Version 1.0. Overview Nullable Datatype Description ? HasValue Lifted Conversions null coalescing operator ?? Partial Classes Copyright.
BUILDING JAVA PROGRAMS CHAPTER 2 PRIMITIVE DATA TYPES AND OPERATIONS.
C# EMILEE KING. HISTORY OF C# In the late 1990’s Microsoft recognized the need to be able to develop applications that can run on multiple operating system.
Copyright © 2012 Pearson Education, Inc. Chapter 6 More Conditionals and Loops Java Software Solutions Foundations of Program Design Seventh Edition John.
Neal Stublen What’s an indexer?  An array has an indexer… int[] myArray = new int[5]; for (int index = 0; index < 5; ++index) {
Synchronized and Monitors. synchronized is a Java keyword to denote a block of code which must be executed atomically (uninterrupted). It can be applied.
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
 2008 Pearson Education, Inc. All rights reserved Operator Overloading.
Overriding toString()
Module 8: Delegates and Events. Overview Delegates Multicast Delegates Events When to Use Delegates, Events, and Interfaces.
Bill Campbell, UMB Microsoft's.NET C# and The Common Language Runtime.
ITI 1120 Lab #11 Contributors: Diana Inkpen, Daniel Amyot, Sylvia Boyd, Amy Felty, Romelia Plesa, Alan Williams.
C# Operator Overloading and Type Conversions C#.NET Software Development Version 1.0.
Operator Overloading Week 5.
CS Object Oriented Programming Using C++
Neal Stublen Tonight’s Agenda  Indexers  Delegates and events  Operator overloading  Class inheritance  Q&A.
Java Nuts and Bolts Variables and Data Types Operators Expressions Control Flow Statements Arrays and Strings.
Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
Special Features of C# : Delegates, Events and Attributes.
Events Programming in C# Events CSE 494R (proposed course for 459 Programming in C#) Prof. Roger Crawfis.
2: Basics Basics Programming C# © 2003 DevelopMentor, Inc. 12/1/2003.
© 2006 Pearson Addison-Wesley. All rights reserved 1-1 Chapter 1 Review of Java Fundamentals.
1 Advanced Programming IF. 2 Control Structures Program of control –Program performs one statement then goes to next line Sequential execution –Different.
Module 13: Properties and Indexers. Overview Using Properties Using Indexers.
COMP Inheritance and Polymorphism Yi Hong June 09, 2015.
And other languages…. must remember to check return value OR, must pass label/exception handler to every function Caller Function return status Caller.
Operators and Cast. Operators Operator Shortcuts.
Preface IIntroduction Course Objectives I-2 Oracle Complete Solution I-3 Course Agenda I-4 Tables Used in This Course I-5 The Order Entry Schema I-6 The.
Value Types. 2 Objectives Discuss concept of value types –efficiency –memory management –value semantics –boxing –unboxing –simple types Introduce struct.
ITI 1120 Lab #10 Objects and Classes Slides by: Romelia Plesa, Sylvia Boyd, Alan Williams, Diana InkPen, Daniel Amyot, Gilbert Arbez, Mohamad Eid.
Chapter 7: Expressions and Assignment Statements
C# Operator Overloading and Type Conversions
16: Equals Equals Programming C# © 2003 DevelopMentor, Inc. 12/1/2003.
Java Primer 1: Types, Classes and Operators
Operators Overloading
Delegates and Events 14: Delegates and Events
Methods Attributes Method Modifiers ‘static’
Chapter 7: Expressions and Assignment Statements
The switch Statement The switch statement provides another way to decide which statement to execute next The switch statement evaluates an expression,
The dirty secrets of objects
CS 302 Week 11 Jim Williams, PhD.
Implementing Polymorphism
C# Event Processing Model
בניית מחלקות.
Java Programming Language
בניית מחלקות.
Delegates & Events 1.
Building Java Programs
CS139 October 11, 2004.
CIS 199 Final Review.
DELEGATES AND EVENT MODELING
ENERGY 211 / CME 211 Lecture 5 October 1, 2008.
Presentation transcript:

Module 12: 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 = Int.Add(myIntVar2, Int.Add(Int.Add(myIntVar3, myIntVar4), 33)); myIntVar1 = myIntVar2 + myIntVar3 + myIntVar4 + 33;

Predefined C# Operators Operator Categories ArithmeticMember access Logical (Boolean and bitwise) Indexing String concatenationCast Increment and decrementConditional ShiftDelegate concatenation and removal RelationalObject creation AssignmentType information Overflow exception controlIndirection 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 Operator op, 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); } 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 != 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) {... } 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) {...} 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) {...}

Quiz: Spot the Bugs public bool operator != (Time t1, Time t2) {... } public bool operator != (Time t1, Time t2) {... } 11 public static operator float(Time t1) {... } 22 public static Time operator += (Time t1, Time t2) {... } public static Time operator += (Time t1, Time t2) {... } public static bool Equals(Object obj) {... } public static int operator implicit(Time t1) {...} public static int operator implicit(Time t1) {...} 55

Lab 12.1: Defining Operators

 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 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( ); public delegate void StartPumpCallback( );... StartPumpCallback callback;... callback = new StartPumpCallback(ed1.StartElectricPumpRunning);... callback( ); No Method Body Call Here No Call Here

 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; public delegate void StartPumpCallback( ); private event StartPumpCallback CoreOverheating; PneumaticPumpDriver pd1 = new PneumaticPumpDriver( );... CoreOverheating += new StartPumpCallback(pd1.SwitchOn); PneumaticPumpDriver pd1 = new PneumaticPumpDriver( );... CoreOverheating += new StartPumpCallback(pd1.SwitchOn); public void SwitchOnAllPumps( ) { if (CoreOverheating != null) { CoreOverheating( ); } 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

Demonstration: Handling Events

Lab 12.2: Defining and Using Events

Review Introduction to Operators Operator Overloading Creating and Using Delegates Defining and Using Events

Course Evaluation