C# part II Delegates and Events Delegates and Events Dynamic functions Dynamic functions Extension methods Extension methods Closures Closures.

Slides:



Advertisements
Similar presentations
CHARLES UNIVERSITY IN PRAGUE faculty of mathematics and physics C# Language &.NET Platform 12 th -13 th Lecture Pavel Ježek.
Advertisements

1 Derived Classes and Inheritance Chapter Objectives You will be able to: Create derived classes in C#. Understand polymorphism. Write polymorphic.
CS 4800 By Brandon Andrews.  Specifications  Goals  Applications  Design Steps  Testing.
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++
C#C# C using System; public class MyClass } public static void Main() { Console.WriteLine("Hello, World!"); } } using System; public class MyClass } public.
Differences between C# and C++ Dr. Catherine Stringfellow Dr. Stewart Carpenter.
C# Tutorial From C++ to C#. Some useful links Msdn C# us/library/kx37x362.aspxhttp://msdn.microsoft.com/en- us/library/kx37x362.aspx.
CHARLES UNIVERSITY IN PRAGUE faculty of mathematics and physics C# Language &.NET Platform 7 th & 8 th Lecture Pavel Ježek.
220 FINAL TEST REVIEW SESSION Omar Abdelwahab. INHERITANCE AND POLYMORPHISM Suppose you have a class FunClass with public methods show, tell, and smile.
Advanced .NET Programming I 13th Lecture
Lecture 9 Polymorphism Richard Gesick.
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
Java2C# Antonio Cisternino Part II. Outline Array types Enum types Value types  differences from classes  boxing and unboxing Delegate types  Base.
C#C# Classes & Methods CS3260 Dennis A. Fairclough Version 1.1 Classes & Methods CS3260 Dennis A. Fairclough Version 1.1.
Distributed Systems (236351) Tutorial 1 - Getting Started with Visual Studio C#.NET.
Class Inheritance UNC-CHAPEL HILL COMP 401 BRIAN CRISTANTE 5 FEBRUARY 2015.
CS212: Object Oriented Analysis and Design Lecture 6: Friends, Constructor and destructors.
Introduction to C# C# is - elegant, type-safe, object oriented language enabling to build applications that run on the.NET framework - types of applications.
1 COSC3557: Object-Oriented Programming Haibin Zhu, Ph. D. Associate Professor of CS, Nipissing University.
Delegates Programming in C# Delegates CSE 494R (proposed course for 459 Programming in C#) Prof. Roger Crawfis.
Session 08 Module 14: Generics and Iterator Module 15: Anonymous & partial class & Nullable type.
Modern Software Development Using C#.NET Chapter 5: More Advanced Class Construction.
E FFECTIVE C# 50 Specific Ways to Improve Your C# Second Edition Bill Wagner محمد حسین سلطانی.
Introduction to C#. Why C#? Develop on the Following Platforms ASP.NET Native Windows Windows 8 / 8.1 Windows Phone WPF Android (Xamarin) iOS (Xamarin)
Programming in Java CSCI-2220 Object Oriented Programming.
C# Classes and Inheritance CNS 3260 C#.NET Software Development.
1 Interfaces and Abstract Classes Chapter Objectives You will be able to: Write Interface definitions and class definitions that implement them.
Computing with C# and the.NET Framework Chapter 2 C# Programming Basics ©2003, 2011 Art Gittleman.
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.
COP3502 Programming Fundamentals for CIS Majors 1 Instructor: Parisa Rashidi.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 9 Inheritance and.
CHARLES UNIVERSITY IN PRAGUE faculty of mathematics and physics Advanced.NET Programming I 10 th Lecture Pavel Ježek
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 6 Objects and Classes.
FEN 2014UCN Teknologi/act2learn1 Higher order functions Observer Pattern Delegates Events Visitor Pattern Lambdas and closures Lambdas in libraries.
Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
 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.
Polymorphism, Virtual Methods and Interfaces Version 1.1.
Special Features of C# : Delegates, Events and Attributes.
Effective C# 50 Specific Way to Improve Your C# Item 22, 23.
CHARLES UNIVERSITY IN PRAGUE faculty of mathematics and physics C# Language &.NET Platform 4 th Lecture Pavel Ježek
- This slide is intentionally left blank - Some of the slides are based on University of Linz.NET presentations. © University of Linz, Institute for System.
1 C# - Inheritance and Polymorphism. 2 1.Inheritance 2.Implementing Inheritance in C# 3.Constructor calls in Inheritance 4.Protected Access Modifier 5.The.
© 2006 Pearson Addison-Wesley. All rights reserved 1-1 Chapter 1 Review of Java Fundamentals.
Module 13: Properties and Indexers. Overview Using Properties Using Indexers.
Arrays & Enum & Events. Arrays Arrays are data structures consisting of related data items of the same type. Arrays are fixed-length entities—they remain.
C# Fundamentals An Introduction. Before we begin How to get started writing C# – Quick tour of the dev. Environment – The current C# version is 5.0 –
 The word static is used to declare either a ________ variable or method.  Why do we use statics?  What is Polymorphism? class In general, we use a.
C# for C++ Programmers 1.
C# - OOP TTU IT College , Autumn SEMESTER Andres käver.
Advanced .NET Programming I 3nd Lecture
Ch 10- Advanced Object-Oriented Programming Features
Inheritance and Polymorphism
Delegates and Events 14: Delegates and Events
Methods Attributes Method Modifiers ‘static’
Computing with C# and the .NET Framework
CS360 Windows Programming
C# In many ways, C# looks similar to Java
Lecture 23 Polymorphism Richard Gesick.
.NET and .NET Core 5.2 Type Operations Pan Wuming 2016.
Chapter 9 Inheritance and Polymorphism
.NET and .NET Core 9. Towards Higher Order Pan Wuming 2017.
6 Delegate and Lambda Expressions
Conditional Statements
Delegates & Events 1.
Module 2 Variables, Assignment, and Data Types
CIS 199 Final Review.
5. 3 Coding with Denotations
Chengyu Sun California State University, Los Angeles
Presentation transcript:

C# part II Delegates and Events Delegates and Events Dynamic functions Dynamic functions Extension methods Extension methods Closures Closures

2 Events and Delegates C# Terminology –Event: a field representing a multi-set of delegates Defined with event keyword Operations –Add delegate using += operator += has default implementation, but user can provide his own add. –Remove delegate using -= operator -= has a default implementation, but user can provide his own del. –Call all delegates in the multi-set –Delegate: type safe function pointer defined with delegate keyword part of the class hierarchy Classical Example: when a button is pressed, listeners should be notified with "callback functions" Our Example: royal social conduct –If King is happy: notify all men in the kingdom –If King is ill: notify noblemen only.

3 Kingdom namespace King, Nobleman and Citizens Man abstract Citizen sealed Nobleman concrete King concrete Life static Name: every man has a name Title: every man has a title, based on his status and name –Realized by method ToString() Service: every man can be set to service any number of kings. –Method service(King k) in class Man State enum Notify delegate

4 Delegate Notify Type Definition: pointer to a function (to be called when a king changes his state) namespace Kingdom { delegate Object Notify(King k); … } Simple (uninteresting) use: void foo(King k) { Notify bar; // A variable of type Notify bar = new Notify( FunctionDescriptor ); … Object o = bar(k); // Invoke FunctionDescriptor } More interesting use: class Foo { event Notify baz; // A multi-set of variables of type Notify public void foo(King k) { baz += new Notify( FunctionDescriptor ); … Object o = baz(k); // Invoke FunctionDescriptor } } Notify delegate

5 Class King and Enum State namespace Kingdom { … enum State { happy, ill }; class King : Man { public State state; public King(String name): base(name){state = State.ill;} sealed override public String ToString() { return "His Majesty, King " + Name; } // public multi-sets of those interested in the King's being. public event Notify when_ill, when_happy; public Object become_ill() { // returns last listener return value state = State.ill; return when_ill != null ? when_ill(this) : null; } public Object become_happy() { // returns last listener return value state = State.happy; return when_happy != null ? when_happy(this) : null; } … } State enum King concrete

6 Class Man namespace Kingdom { abstract class Man { protected readonly String Name; public Man(String name) { Name = name; } abstract override public String ToString(); // Every man is happy when a King he serves is happy. virtual public void serve(King k) { k.when_happy += new Notify(happy); } public Man happy(Object other) { Console.WriteLine(this + " is happy to hear that " + other + " is happy."); return this; } {... } Man abstract

7 Delegates and Events Delegate type definition: pointer to a function (to be called when a king changes his state) namespace Kingdom { delegate Object Notify(King k); … } Event definition: a field with a multi-set of delegates namespace Kingdom { class King: Man { public event Notify when_ill, when_happy; … } It is possible (but not very useful) to define a field which contains a single delegate. class KING: King { public Notify queen_listner; }

8 Registration of an Actual Delegate Actual Delegate: a function for notification namespace Kingdom { … abstract class Man { public Man happy(Object other) { Console.WriteLine(this + " is happy to hear that " + other + " is happy."); return this; } } … } … Register a delegate: with += operator namespace Kingdom { abstract class Man { virtual public void serve(King k) { k.when_happy += new Notify(happy); } }

9 Classes Citizen and Nobleman namespace Kingdom { … sealed class Citizen: Man { public Citizen(String name) : base(name) { } override public String ToString() { return "Citizen " + Name;} } class Nobleman: Man { public Nobleman(String name) : base(name) { } override public String ToString() { return "Nobleman " + Name;} public Nobleman ill(Object other) { Console.WriteLine(this + " is sorry to hear that " + other + " is ill."); return this; } override public void serve(King k) { base.serve(k); k.when_ill += new Notify(ill); } } { Citizen sealed Nobleman concrete

10 static class Life { static void Main() { King R = new King("Richard"), G = new King("George"); Citizen a = new Citizen("Al"), b = new Citizen("Bob"); Nobleman v = new Nobleman("Virgil"); a.serve(R); b.serve(R); b.serve(G); v.serve(R); G.serve(R); R.become_ill(); R.become_happy(); Console.WriteLine("----"); G.become_ill(); G.become_happy(); Console.WriteLine("----"); } Main Application Al Bob Virgil Richard George Life static

11 Output Noblemen Virgil is sorry to hear that His Majesty, King Richard is ill. Citizen Al is happy to hear that His Majesty, King Richard is happy. Citizen Bob is happy to hear that His Majesty, King Richard is happy. Noblemen Virgil is happy to hear that His Majesty, King Richard is happy. His Majesty, King George is happy to hear that His Majesty, King Richard is happy Citizen Bob is happy to hear that His Majesty, King George is happy Scenario 1.King Richard becomes ill 2.King Richard becomes happy 3.King George becomes ill 4.King George becomes happy Remember, every man is happy when a king he serves is happy, but only a Noblemen is to be notified when his king is ill. Al Bob Virgil Richard George

12 Delegate Variance Delegate definition: delegate Object Notify(King k); Actual delegates: public Man happy(Object other) {…} public Nobleman ill(Object other){…} Variance: –Return Type: Co-Variant –Arguments Type: Contra-Variant –Static / Non-static: both static and non-static actuals may be used. Compatibility Rules: Allow a specific listener to subscribe to a more general event distribution channel –It is OK to pass an actual King argument to the listener happy(Object other) –Event triggering expects an Object, and is type safe even if a Man or a Nobleman is returned.

13 Delegate Type Hierarchy using System; using System.Reflection; delegate Object MyDelegateType(Type o); public static class DelegateTypeHierarchy { private static String pName(Type t) { as before... } private static void ancestory(Object o){ as before … } public static void Main() { ancestory(new MyDelegateType(pName)); } } using System; using System.Reflection; delegate Object MyDelegateType(Type o); public static class DelegateTypeHierarchy { private static String pName(Type t) { as before... } private static void ancestory(Object o){ as before … } public static void Main() { ancestory(new MyDelegateType(pName)); } } MyDelegateType inherits from System.MulticastDelegate System.MulticastDelegate inherits from System.Delegate System.Delegate inherits from System.Object System.Object inherits from null

14 Reflection Relevant namespaces: – System.Reflection; – System.Reflection.Emit; The Reflection API allows a C# program to inspect itself –gets the type from an existing object –dynamically creates an instance of a type –invokes the type's methods –accesses fields and properties of the object –… The Reflection API allows a C# program to manipulate itself –adds new types at runtime –adds new methods to a type at runtime –…

15 Dynamic methods public delegate void PrintDelegate (); public PrintDelegate Create(string message) { MethodInfo writeLineMethod = typeof(Console).GetMethod("WriteLine", new Type[]{typeof(string)} ); Module currentModule = Assembly.GetExecutingAssembly().GetModules()[0]; DynamicMethod method = new DynamicMethod("PrintData", typeof(void), new Type[0], currentModule); ILGenerator ilGenerator = method.GetILGenerator(); ilGenerator.Emit( OpCodes.Ldstr, message); ilGenerator.Emit( OpCodes.Call, writeLineMethod); ilGenerator.Emit( OpCodes.Ret ); PrintDelegate ret = method.CreateDelegate(typeof(PrintDelegate ) ) as PrintDelegate; return ret; } public delegate void PrintDelegate (); public PrintDelegate Create(string message) { MethodInfo writeLineMethod = typeof(Console).GetMethod("WriteLine", new Type[]{typeof(string)} ); Module currentModule = Assembly.GetExecutingAssembly().GetModules()[0]; DynamicMethod method = new DynamicMethod("PrintData", typeof(void), new Type[0], currentModule); ILGenerator ilGenerator = method.GetILGenerator(); ilGenerator.Emit( OpCodes.Ldstr, message); ilGenerator.Emit( OpCodes.Call, writeLineMethod); ilGenerator.Emit( OpCodes.Ret ); PrintDelegate ret = method.CreateDelegate(typeof(PrintDelegate ) ) as PrintDelegate; return ret; }

16 Anonymous Methods Anonymous methods represent a way to pass a code block as a delegate parameter. delegate void Printer(string s); class AnonymousMethods{ static void Main() { Printer p = delegate(string j) { System.Console.WriteLine(j); }; p("The delegate using the anonymous method is called."); p = new Printer(AnonymousMethods.DoWork); p("The delegate using the named method is called."); } static void DoWork(string k) { System.Console.WriteLine(k); } delegate void Printer(string s); class AnonymousMethods{ static void Main() { Printer p = delegate(string j) { System.Console.WriteLine(j); }; p("The delegate using the anonymous method is called."); p = new Printer(AnonymousMethods.DoWork); p("The delegate using the named method is called."); } static void DoWork(string k) { System.Console.WriteLine(k); } The delegate using the anonymous method is called. The delegate using the named method is called.

17 Anonymous Methods (2) delegate void Printer2(); class AnonymousMethods{ static void Main() { string j = "The delegate with local variable is called."; Printer2 p2 = delegate() { System.Console.WriteLine(j); }; p2(); } delegate void Printer2(); class AnonymousMethods{ static void Main() { string j = "The delegate with local variable is called."; Printer2 p2 = delegate() { System.Console.WriteLine(j); }; p2(); } The delegate with local variable is called.

18 Lambda Expressions A lambda expressions is an anonymous function, that use the lambda operator =>. –The left side of the lambda operator specifies the input parameters (if any) –The right side holds the expression or statement block delegate void Printer(string s); class LambdaExpressions{ static void Main() { Printer p = j => System.Console.WriteLine(j); p("The delegate using the anonymous method is called."); } delegate void Printer(string s); class LambdaExpressions{ static void Main() { Printer p = j => System.Console.WriteLine(j); p("The delegate using the anonymous method is called."); } The delegate using the anonymous method is called.

19 Yield Return Iterator "yield" keyword is used to iterate through objects returned by a method. class Team { String s1 = "Brayent"; String s2 = "Parker"; String s3 = "Pual"; public IEnumerable getPlyares() { for (int i = 1; i < 4; i++) switch (i) { case 1: yield return s1; break; case 2: yield return s2; break; case 3: yield return s3; break; } class Team { String s1 = "Brayent"; String s2 = "Parker"; String s3 = "Pual"; public IEnumerable getPlyares() { for (int i = 1; i < 4; i++) switch (i) { case 1: yield return s1; break; case 2: yield return s2; break; case 3: yield return s3; break; } static void Main() { Team t = new Team(); foreach (String player in t.getPlyares()) Console.WriteLine(player); } static void Main() { Team t = new Team(); foreach (String player in t.getPlyares()) Console.WriteLine(player); }

20 More about Yield An iterator is a method, get accessor or operator that enables you to support foreach iteration in a class or struct. The yield statement can only appear inside an iterator block. yield return –expression is evaluated and returned as a value to the enumerator object. –expression has to be implicitly convertible to the yield type of the iterator. –A yield return statement cannot be located anywhere inside a try-catch block. –A yield statement cannot appear in an anonymous method. yield break –The operation unconditionally returns control to the caller of the iterator. –A yield break statement cannot be located in a finally block. –A yield statement cannot appear in an anonymous method.

21 Extension methods Extension methods are a special kind of static method Extension methods allow to "add" methods to existing types without modifying the original type public static class Extension { public static bool IsNullOrEmpty(this string s) { return (s == null || s.Trim().Length == 0); } public static bool IsLengthEquals(this string s, int length){ return (s != null && s.Length == length); } public static class Extension { public static bool IsNullOrEmpty(this string s) { return (s == null || s.Trim().Length == 0); } public static bool IsLengthEquals(this string s, int length){ return (s != null && s.Length == length); } static void Main(string[] args) { string newString = null; if (newString.IsNullOrEmpty()) { // Do Something1 } if (newString.IsLengthEquals(3)) { // Do Something2 } static void Main(string[] args) { string newString = null; if (newString.IsNullOrEmpty()) { // Do Something1 } if (newString.IsLengthEquals(3)) { // Do Something2 }

22 Rules for the extension methods The first parameter specifies which type the method operates on –the parameter is preceded by this modifier Extension methods can be used only when the namespace in which the methods are defined is explicitly imported with a using directive. Extension methods cannot access private variables in the type they are extending Extension methods can extend a class or interface An extension method with the same name and signature as an interface or class method will never be called. –At compile time, extension methods always have lower priority than instance methods defined in the type itself

23 Summary – C# Unique Features Properties and Indexers: implement fields with functions –Conforms to Eiffel Principle of Uniform Reference. Delegates: type safe function pointers –Events: list of delegates. Static classes Seamless integration of value semantics –Including nullable values. Default Strict Inheritance –override and new keywords