CS 3260.  C++ Function Pointers  C# Method References  Groundwork for Lambda Functions.

Slides:



Advertisements
Similar presentations
Object Oriented Programming with Java
Advertisements

Object-Oriented programming in C++ Classes as units of encapsulation Information Hiding Inheritance polymorphism and dynamic dispatching Storage management.
Inheritance. Many objects have a hierarchical relationship –Examples: zoo, car/vehicle, card game, airline reservation system Inheritance allows software.
Copyright © 2012 Pearson Education, Inc. Chapter 9 Delegates and Events.
METHOD OVERRIDING 1.Sub class can override the methods defined by the super class. 2.Overridden Methods in the sub classes should have same name, same.
Object-Oriented PHP (1)
OOP in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
C#.NET C# language. C# A modern, general-purpose object-oriented language Part of the.NET family of languages ECMA standard Based on C and C++
Delegates and Events Tom Roeder CS fa. Motivation – Function Pointers Treat functions as first-class objects eg. Scheme: (map myfunc somelist)
C# Event Processing Model Solving The Mystery. Agenda Introduction C# Event Processing Macro View Required Components Role of Each Component How To Create.
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.
Comp 248 Introduction to Programming Chapter 4 - Defining Classes Part A Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Taken from slides of Starting Out with C++ Early Objects Seventh Edition.
220 FINAL TEST REVIEW SESSION Omar Abdelwahab. INHERITANCE AND POLYMORPHISM Suppose you have a class FunClass with public methods show, tell, and smile.
Writing Classes (Chapter 4)
C# Programming Fundamentals of Object-Oriented Programming Fundamentals of Object-Oriented Programming Introducing Microsoft.NET Introducing Microsoft.NET.
C#C# Classes & Methods CS3260 Dennis A. Fairclough Version 1.1 Classes & Methods CS3260 Dennis A. Fairclough Version 1.1.
Programming Languages and Paradigms Object-Oriented Programming (Part II)
Inheritance in the Java programming language J. W. Rider.
Tuc Goodwin  Object and Component-Oriented Programming  Classes in C#  Scope and Accessibility  Methods and Properties  Nested.
One of the most prevalent powerful programming languages.
Copyright 2004 Scott/Jones Publishing Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 7 Structured Data and Classes.
ECE122 Feb. 22, Any question on Vehicle sample code?
OOP: Encapsulation,Abstraction & Polymorphism. What is Encapsulation Described as a protective barrier that prevents the code and data being randomly.
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
Copyright 2006 Oxford Consulting, Ltd1 February Polymorphism Polymorphism Polymorphism is a major strength of an object centered paradigm Same.
C# Classes and Inheritance CNS 3260 C#.NET Software Development.
Inheritance, Polymorphism, And Virtual Functions Chapter 15.
What Is Inheritance? Provides a way to create a new class from an existing class New class can replace or extend functionality of existing class Can be.
Module 8: Delegates and Events. Overview Delegates Multicast Delegates Events When to Use Delegates, Events, and Interfaces.
Rina System development with Java Instructors: Rina Zviel-Girshin Lecture 4.
Classes. Constructor A constructor is a special method whose purpose is to construct and initialize objects. Constructor name must be the same as the.
OOP in C++ CS 124. Program Structure C++ Program: collection of files Source (.cpp) files be compiled separately to be linked into an executable Files.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 9 Java Fundamentals Objects/ClassesMethods Mon.
CS-1030 Dr. Mark L. Hornick 1 Basic C++ State the difference between a function/class declaration and a function/class definition. Explain the purpose.
FEN 2014UCN Teknologi/act2learn1 Higher order functions Observer Pattern Delegates Events Visitor Pattern Lambdas and closures Lambdas in libraries.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
Introduction to Object-Oriented Programming Lesson 2.
1.NETDelegates & eventsNOEA / PQC Delegates & events Observer pattern Delegates –Semantics –Cil – kode –Anvendelse Events.
From C++ to C# Part 5. Enums Similar to C++ Similar to C++ Read up section 1.10 of Spec. Read up section 1.10 of Spec.
Chapter 9 Delegates and Events. Copyright 2006 Thomas P. Skinner2 Delegates Delegates are central to the.NET FCL A delegate is very similar to a pointer.
Special Features of C# : Delegates, Events and Attributes.
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
POLYMORPHISM Chapter 6. Chapter Polymorphism  Polymorphism concept  Abstract classes and methods  Method overriding  Concrete sub classes and.
1.NETDelegates & eventsNOEA / PQC 2007 Delegates & events Observer pattern Delegates –Semantics –Cil – kode –Anvendelse Events.
Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 6-1 Learning Objectives  Classes  Constructors  Principles of OOP  Class type member.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 10 Java Fundamentals Objects/ClassesMethods.
Basic Class Structure. Class vs. Object class - a template for building an object –defines the instance data that the object will hold –defines instance.
Unit 2. Constructors It initializes an object when it is created. It has same as its class and syntactically similar to a method. Constructor have no.
Classes CS 162 (Summer 2009). Parts of a Class Instance Fields Methods.
Chapter 5 Introduction to Defining Classes Fundamentals of Java.
Inheritance Modern object-oriented (OO) programming languages provide 3 capabilities: encapsulation inheritance polymorphism which can improve the design,
C# for C++ Programmers 1.
Delegates and Events Svetlin Nakov Telerik Corporation
Inheritance and Polymorphism
Delegates and Events 14: Delegates and Events
Inheritance Modern object-oriented (OO) programming languages provide 3 capabilities: encapsulation inheritance polymorphism which can improve the design,
C# Event Processing Model
Corresponds with Chapter 7
6 Delegate and Lambda Expressions
Delegates & Events 1.
Lesson 7. Events, Delegates, Generics.
Fundaments of Game Design
CIS 199 Final Review.
Class.
Java Programming Language
Creating and Using Classes
Events, Delegates, and Lambdas
Presentation transcript:

CS 3260

 C++ Function Pointers  C# Method References  Groundwork for Lambda Functions

 int (*)(int,double) fPtr;

 A delegate type represents references to methods with a particular parameter list and return type. Delegates make it possible to treat methods as entities that can be assigned to variables and passed as parameters.  Delegates make it possible to treat methods as entities that can be assigned to variables and passed as parameters.

 Delegates provide the groundwork for Lambda Functions.  Lambda Functions will be discussed in a later lesson.

 Reference Type  Delegate Type Declaration  delegate void MyDelegate(int ival, double dval);  Delegate Variable Declaration & Assignment  MyDelegate mdel = new MyDelegate(MyMethod); or  MyDelegate mdel = MyMethod; or  mdel += TestMethod;  Method Declaration  void MyMethod(int iv,double dv){ … }  Void TestMethod(int j,double k){…}  Method Call via the Delegate  mdel(100,5.5);  Type-Safe  Can have generic parameters

Copyright © by Dennis A. Fairclough all rights reserved. 7  A delegate-declaration is a type-declaration (§9.5) that declares a new delegate type.§9.5  delegate-declaration: attributes opt delegate-modifiers opt delegate return-type identifier(formal- parameter-list opt ) ; delegate-modifiers: delegate-modifier delegate-modifiers delegate-modifier delegate-modifier: new public protected internal private  Example public delegate void D(int x);

Copyright © by Dennis A. Fairclough all rights reserved. 8  A delegate declaration defines a new type  Delegates are similar to function pointers  C++ function pointer -> int (*)(int,double);  Delegates are type-safe  Delegates are object-oriented  A form of polymorphism  Delegate types are derived from System.MulticastDelegate

Copyright © by Dennis A. Fairclough all rights reserved. 9 Exposed Command VariableCommand object instance Command executor Command Class Execute() Command issuer Command Subclass Execute() Knows when the event happens but doesn’t know what to do about it Knows what to do when an event happens but doesn’t know when

Copyright © by Dennis A. Fairclough all rights reserved. 10 Delegate Host Class (Publisher) Exposed Delegate Knows when the event happens but doesn’t know what to do about it Delegate User Class (Subscriber) Knows what to do when an event happens but doesn’t know when Subscribing Method AKA: The Observer Pattern or.NET Event Model

Copyright © by Dennis A. Fairclough all rights reserved. 11  When you want different things to happen when an event occurs  GUI events ->  this.BtnExit.Click += new System.EventHandler(this.BtnExit_Click);  private void BtnExit_Click(object sender, EventArgs e) { Close(); }  Threading situations  Callbacks  Command Pattern  To keep your interface clean  Looser coupling

Copyright © by Dennis A. Fairclough all rights reserved. 12  three steps: 1. Delegate Declaration 2. Delegate Instantiation 3. Function Declaration 4. Delegate Invocation (call)

Copyright © by Dennis A. Fairclough all rights reserved. 13 namespace some_namespace { delegate void MyDelegate(int x, int y); //namespace scope class MyClass { public delegate int AnotherDelegate(object o, int y); //class scope } Delegate Name (Type)

Copyright © by Dennis A. Fairclough all rights reserved. 14 delegate void MyDelegate(int x, int y); //namespace scope class MyClass { private MyDelegate myDelegate = new MyDelegate( SomeFun ); public static void SomeFun(int dx, int dy) { //method body } Invocation Method name (no params or parens)

Copyright © by Dennis A. Fairclough all rights reserved. 15 class MyClass { private MyDelegate myDelegate; //class scope public MyDelegate MyDelegate { set { this.myDelegate = value; } } class MainClass { [STAThread] static void Main() { MyClass mc = new MyClass(); mc.MyDelegate = new MyDelegate( MainClassMethod ); } private static void MainClassMethod(int x, int y) { } } Delegate Variable (null) Passed in and assigned in the constructor

Copyright © by Dennis A. Fairclough all rights reserved. 16 class MyClass { private MyDelegate myDelegate; public MyDelegate MyDelegate { set { this.MyDelegate = value; } } class MainClass { [STAThread] static void Main() { MainClass mainClass = new MainClass(); MyClass mc = new MyClass(); mc.MyDelegate = new MyDelegate( mainClass.MainClassMethod ); } private void MainClassMethod(int x, int y) { } } Method attached to an instance

Copyright © by Dennis A. Fairclough all rights reserved. 17  A Method is compatible with a Delegate if and only if:  They have the same type and number of parameters  They have the same return type  Name?

Copyright © by Dennis A. Fairclough all rights reserved. 18 class MyClass { private MyDelegate myDelegate; public MyClass(MyDelegate myDelegate) { this.MyDelegate = myDelegate; } private void WorkerMethod() { int x = 500, y = 1450; if(myDelegate != null) myDelegate(x, y); } Attempting to invoke a delegate instance whose value is null results in an exception of type System.NullReferenceException.

Copyright © by Dennis A. Fairclough all rights reserved. 19  Delegate is really an array of function pointers  Now when Invoked, mc.MyDelegate will execute all three Methods  Notice that you don’t have to instantiate the delegate before using +=  The compiler does it for you when calling += mc.MyDelegate += new MyDelegate( mc.Method1 ); mc.MyDelegate += new MyDelegate( mc.Method2 ); mc.MyDelegate = mc.MyDelegate + new MyDelegate( mc.Method3 );

Copyright © by Dennis A. Fairclough all rights reserved. 20  Methods are executed in the order they are added  Add methods with + or +=  Remove methods with - or -=  Attempting to remove a method that does not exist is not an error  Return value is whatever the last method returns  A delegate may be present in the invocation list more than once  The delegate is executed as many times as it appears (in the appropriate order)  Removing a delegate that is present more than once removes only the last occurrence

Copyright © by Dennis A. Fairclough all rights reserved. 21 mc.MyDelegate = new MyDelegate( mc.Method1 ); mc.MyDelegate += new MyDelegate( mc.Method2 ); mc.MyDelegate = mc.MyDelegate + new MyDelegate( mc.Method3 ); // The call to: mc.MyDelegate(0, 0); // executes: // mc.Method1 // mc.Method2 // mc.Method3 (See Delegates Demo)

public delegate int TestDel(int iv); //delegate declaration TestDel delref = new TestDel(FooBar);//delegate initialization delref += FooBar;//Short form delref += Method0;//chaining a delegate delref -= FooBar;//unchaining a delegate delref = delegate (int x){ return x + 100; } //anynomous method static public int FooBar(int ival){ … return i; }//Method static public int Method0(int x){ … return x; } //Other method Copyright © by Dennis A. Fairclough all rights reserved. 22

Copyright © by Dennis A. Fairclough all rights reserved. 23  abstract  Special  Only the system and compiler can inherit from System.Delegate  Members:  Method  Returns A MethodInfo object  Target  The ‘this’ pointer belonging to the method  null if the method was static  operator == and operator !=

Copyright © by Dennis A. Fairclough all rights reserved. 24  Target  Method  operator== and operator !=  _prev  Linked list of System.Delegate objects  GetInvocationList()  Returns the Invocation List as a Delegate[]

Copyright © by Dennis A. Fairclough all rights reserved. 25  Exposing a delegate might be bad if:  You don’t want others to invoke your delegate  You have assigned to the delegate internally  Enter the event keyword...

 delegate T Gdelegate (T tval,K kval);  Func<> Func  Func  Action<> void Action  void Action

Copyright © by Dennis A. Fairclough all rights reserved. 27  Events are “safe” delegates  But they are delegates  Restricts use of the delegate (event) to the target of a += or -= operation  No assignment  No invocation  No access of delegate members (like GetInvocation List)  Allow for their own Exposure  Event Accessors

Copyright © by Dennis A. Fairclough all rights reserved. 28 public delegate void FireThisEvent(); class MyEventWrapper { private event FireThisEvent fireThisEvent; public void OnSomethingHappens() { if(fireThisEvent != null) fireThisEvent(); } public event FireThisEvent FireThisEvent { add { fireThisEvent += value; } remove { fireThisEvent -= value; } } add and remove keywords (See Event Demo)

Copyright © by Dennis A. Fairclough all rights reserved. 29  Exceptions thrown from a delegate:  Are thrown to the calling context  All subsequent delegates in the Invocation List are ignored

Copyright © by Dennis A. Fairclough all rights reserved. 30  ThreadStart  TimerCallback  ASyncCallback  EventHandler  KeyPressEventHandler  KeyEventHandler  etc.

Copyright © by Dennis A. Fairclough all rights reserved. 31  ??