SlideShare a Scribd company logo
1 of 42
Download to read offline
C#:	
  Delegates,	
  Events	
  and	
  
            Lambda	
  
            Jussi	
  Pohjolainen	
  
Tampere	
  University	
  of	
  Applied	
  Sciences	
  
About	
  Callbacks	
  
•  Callback	
  methods	
  can	
  be	
  implemented	
  in	
  C#	
  
   using	
  delegates,	
  events	
  and	
  lambda	
  
•  Callback	
  method?	
  	
  
    –  When	
  buGon	
  is	
  clicked,	
  a	
  method	
  is	
  called	
  (calls	
  back	
  
       a	
  method	
  you	
  have	
  implemented)	
  
•  Delegate	
  type	
  “points”	
  to	
  a	
  method	
  or	
  a	
  list	
  of	
  
   methods	
  
    –  Event	
  will	
  help	
  you	
  to	
  build	
  callback	
  mechanism	
  
•  Lambda	
  is	
  anonymous	
  method	
  and	
  provides	
  
   simplified	
  approach	
  working	
  with	
  delegates	
  
JavaScript:	
  Callback	
  
function doSomething(integer, someFunction) {
    var i = 0, s = 0;
    for(i = 0; i<integer; i = i + 1) {
        s += integer;
    }

    // callback!
    someFunction(s);
}

function callBackFunction(result) {
    print('result is: ' + result);
}

function main() {
    doSomething(5000, callBackFunction);
}

main();
Java	
  7:	
  Anonymous	
  methods	
  and	
  
                      callbacks	
  
// Kind of hard?
button.addActionListener( new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        // do something
    }
})

// Note: Java 8 will have lambda
Obj-­‐C:	
  Selectors	
  and	
  Callbacks	
  
- (void) testSelectors
{
    SEL variable;
    variable = @selector(animate);

    [self methodWithSelectorAsArgument: variable];
}

- (void) methodWithSelectorAsArgument: (SEL) argument
{
    [self performSelector:argument];
}

- (void) animate
{
    ...
}
Delegate	
  
•  Delegate	
  type	
  holds	
  
   –  Address	
  of	
  the	
  method	
  on	
  which	
  it	
  makes	
  calls	
  
   –  Parameters	
  of	
  the	
  method	
  
   –  Return	
  type	
  of	
  the	
  method	
  
•  Works	
  both	
  asynchronously	
  and	
  
   synchronously.	
  Simplifies	
  things,	
  no	
  need	
  for	
  
   Thread	
  object.	
  Let’s	
  see	
  this	
  later	
  
Example	
  
// Following delegate type can point to whatever
// method as long as it's returning int and it has two
// parameters.
public delegate int Something(int a, int b);

// This will generate a following class! Lot of methods
// also deriving from MulticastDelegate and Delegate (base class
// for MulticastDelegate)
sealed class Something : System.MulticastDelegate
{
    public int Invoke(int x, int y);
    public IAsyncResult BeginInvoke(int x, int y, AsyncCallback cb, object state);
    public int EndInvoke(IAsyncResult result);
}
using System;

public delegate int Something(int a, int b);

class MyMath
{
    public int Add(int a, int b)
    {
        return a + b;
    }
}

class MyMain
{
    public static void Main() {
        MyMath m = new MyMath();
        Something delegateObject = new Something(m.Add);

        Console.WriteLine( delegateObject.Invoke(5,5) );

        // Calls Invoke!
        Console.WriteLine( delegateObject(5,5) );
    }
}
using System;

public delegate int Something(int a, int b);

class MyMath
{
    public static int Add(int a, int b)
    {
        return a + b;
    }
}

class MyMain
{
    public static void Main() {
        Something delegateObject = new Something(MyMath.Add);

        // Calls Invoke!
        Console.WriteLine( delegateObject(5,5) );
    }
}
class MyMain
{
    public static void Main() {
        Something delegateObject = new Something(MyMath.Add);
        PrintInformation(delegateObject);
    }

    // All delegates inherite Delegate class
    public static void PrintInformation(Delegate delObj)
    {
        // Remember that delegate may hold number of methods!
        foreach(Delegate d in delObj.GetInvocationList())
        {
            // Result: Int32 Add(Int32, Int32)
            Console.WriteLine(d.Method);
        }
    }
}
"REAL	
  WORLD"	
  EXAMPLE	
  
class Teacher
{
      // A new inner class is created here! The class inherits
      // System.MulticastDelegate

      // This can point to whatever class that is void and one string
      // argument. This could be also outer-class.
      public delegate void TeacherHandler(string msg);

      // Declare an attribute type of the new class.
      private TeacherHandler listOfHandlers;

      // Helper method for assigning the attribute
      public void RegisterWithListener(TeacherHandler methodToCall)
      {
            listOfHandlers = methodToCall;
      }

      public bool teacherIsBoring { get; set; }

      public void teach()
      {
            // If teacher is not boring
            if(!teacherIsBoring)
            {
                  // And there are someone listening
                  if(listOfHandlers != null)
                  {
                        // Send message to the listener.
                        listOfHandlers("C# is cool!");
                  }
            }
      }
}
using System;

class MyMain
{
     public static void Main()
     {
          Teacher jussi = new Teacher();

                                    // instantiate inner class object
         jussi.RegisterWithListener(new Teacher.TeacherHandler(OnTeachEvent));
         jussi.teacherIsBoring = false;

         jussi.teach();
    }

    // Since teacher is not boring and we are listening,
    // this method is called
    public static void OnTeachEvent(string m)
    {
         Console.WriteLine("Important message from teacher!");
         Console.WriteLine(m);
    }
}
MULTICASTING	
  
// Helper method for assigning the attribute
    public void RegisterWithListener(TeacherHandler methodToCall)
    {
         if(listOfHandlers == null)
         {
              listOfHandlers = methodToCall;
         }
         else
         {
              Delegate.Combine(listOfHandlers, methodToCall);
         }
    }

…

        Teacher jussi = new Teacher();

                                   // instantiate inner class object
        jussi.RegisterWithListener(new Teacher.TeacherHandler(OnTeachEvent1));
        jussi.RegisterWithListener(new Teacher.TeacherHandler(OnTeachEvent2));
        jussi.teacherIsBoring = false;

        jussi.teach();
// Helper method for assigning the attribute
    public void RegisterWithListener(TeacherHandler methodToCall)
    {
         // And even more easier!
         listOfHandlers += methodToCall;
    }

…

        Teacher jussi = new Teacher();

                                   // instantiate inner class object
        jussi.RegisterWithListener(new Teacher.TeacherHandler(OnTeachEvent1));
        jussi.RegisterWithListener(new Teacher.TeacherHandler(OnTeachEvent2));
        jussi.teacherIsBoring = false;

        jussi.teach();
REMOVING	
  TARGETS	
  
class MyMain
{
     public static void Main()
     {
          Teacher jussi = new Teacher();

                                     // instantiate inner class object
          jussi.RegisterWithListener(new Teacher.TeacherHandler(OnTeachEvent1));

          Teacher.TeacherHandler listener;
          jussi.RegisterWithListener(listener = new Teacher.TeacherHandler(OnTeachEvent2));

          jussi.teacherIsBoring = false;
          jussi.teach();

          jussi.UnRegisterWithListener(listener);
          jussi.teach();

     }

..

     // Helper method for assigning the attribute
     public void UnRegisterWithListener(TeacherHandler methodToCall)
     {
          listOfHandlers -= methodToCall;
     }
METHOD	
  GROUP	
  CONVERSION	
  
Method	
  Group	
  Conversion	
  
•  In	
  the	
  previous	
  example,	
  we	
  created	
  object	
  
    –  Teacher.TeacherHandler	
  
•  You	
  don't	
  have	
  to	
  do	
  this!	
  
•  Method	
  group	
  conversion!	
  
    –  Direct	
  method	
  name	
  is	
  converted	
  to	
  a	
  delegate	
  
       object	
  
Method	
  Group	
  Conversion	
  
public static void Main()
{
    Teacher jussi = new Teacher();

    jussi.RegisterWithListener(OnTeachEvent1);
    jussi.RegisterWithListener(OnTeachEvent2);

    jussi.teacherIsBoring = false;
    jussi.teach();

    jussi.UnRegisterWithListener(OnTeachEvent2);
    jussi.teach();

}
EVENTS	
  
Simplify	
  Registering	
  
•  The	
  previous	
  example	
  had	
  methods	
  like	
  
    –  public	
  void	
  RegisterWithListener(TeacherHandler	
  
       methodToCall)	
  
    –  public	
  void	
  
       UnRegisterWithListener(TeacherHandler	
  
       methodToCall)	
  
•  To	
  simplify	
  this,	
  we	
  can	
  use	
  events!	
  
class Teacher
{
       private int workHoursPerDay = 0;

      public delegate void TeacherHandler(string msg);

      // No register or unregister methods!
      //    When using events, two hidden methods are generated:
      //    add_AboutToOverload
      //    remove_AboutToOverLoad
      public event TeacherHandler AboutToOverload;
      public event TeacherHandler MentallyDead;

      public void teach()
      {
             workHoursPerDay++;
             if(workHoursPerDay >= 4 && workHoursPerDay < 6)
             {
                    if(AboutToOverload != null)
                    {
                           AboutToOverload("TOO MUCH WORK FOR ME! Workhours = " + workHoursPerDay);
                    }
             }
             else if(workHoursPerDay >= 6)
             {
                    if(MentallyDead != null)
                    {
                           MentallyDead("CANNOT WORK ANYMORE, BITCH ABOUT THIS! Workhours = " + workHoursPerDay);
                    }
             }
      }
}
class MyMain
{
     public static void Main()
     {
          Student pekka = new Student();
          pekka.Name = "Pekka";
          Supervisor jaska = new Supervisor();
          jaska.Name = "Jaska";

         Teacher jussi = new Teacher();
         jussi.AboutToOverload += pekka.listen;
         jussi.AboutToOverload += jaska.listen;
         jussi.MentallyDead    += jaska.listen;

         jussi.teach();
         jussi.teach();
         jussi.teach();
         jussi.teach();
         jussi.teach();
         jussi.teach();
         jussi.teach();
         jussi.teach();

    }
}
class Student
{
     public string Name {get; set;}
     public void listen(string m)
     {
          Console.WriteLine(Name + " listening to teacher msg = " + m);
     }
}

class Supervisor
{
     public string Name {get; set;}

    public void listen(string m)
    {
         Console.WriteLine(Name + " listening to teacher msg = " + m);
    }
}
RECOMMEND	
  EVENT	
  PATTERN	
  
class Student
{
     public string Name {get; set;}

     // Listener here get information:
    // 1) who is the sender?
    // 2) more information about the event
     public void listen(object sender, TeacherEventArgs events)
     {
          Console.WriteLine(Name + " listening to teacher msg = " + events.msg);
     }
}

class Supervisor
{
     public string Name {get; set;}

    public void listen(object sender, TeacherEventArgs events)
    {
         Console.WriteLine(Name + " listening to teacher msg = " + events.msg);
    }
}
// Implement own custom event!
public class TeacherEventArgs : EventArgs
{
     public readonly string msg;
     public TeacherEventArgs(string message)
     {
          msg = message;
     }
}

// And use it
class Teacher
{
     private int workHoursPerDay = 0;

    public delegate void TeacherHandler(object sender, TeacherEventArgs e);
     …
    public void teach()
    {
         …
          AboutToOverload(this,
                          new TeacherEventArgs("TOO MUCH WORK …"));

         …
    }
EVENTHANDLER<T>	
  DELEGATE	
  
public class TeacherEventArgs : EventArgs
{
     public readonly string msg;
     public TeacherEventArgs(string message)
     {
          msg = message;
     }
}

class Teacher
{
     private int workHoursPerDay = 0;

     /*
       public delegate void TeacherHandler(object sender, TeacherEventArgs e);
       public event TeacherHandler AboutToOverload;
       public event TeacherHandler MentallyDead;
     */

     // Now we can use the EventHandler class. Notice that there is no
     // need for the delegate anymore!
     public event EventHandler<TeacherEventArgs> AboutToOverload;
     public event EventHandler<TeacherEventArgs> MentallyDead;
class MyMain
{
     public static void Main()
     {
          Student pekka = new Student();
          pekka.Name = "Pekka";
          Supervisor jaska = new Supervisor();
          jaska.Name = "Jaska";

          Teacher jussi = new Teacher();

          // Now we can use the   EventHandler class!
          jussi.AboutToOverload   += new EventHandler<TeacherEventArgs>(pekka.listen);
          jussi.AboutToOverload   += jaska.listen;
          jussi.MentallyDead      += jaska.listen;
Anonymous	
  Delegate	
  Methods	
  
Teacher jussi = new Teacher();

jussi.AboutToOverload += delegate (object send, TeacherEventArgs events)
{
     Console.WriteLine("anonymous delegate method 1!");
};

jussi.AboutToOverload += delegate
{
     Console.WriteLine("anonymous delegate method 2!");
};
ABOUT	
  LAMBDA	
  
Lambda	
  Expressions	
  
•  Lambda	
  expression	
  is	
  an	
  anonymous	
  funcon	
  
   that	
  you	
  can	
  use	
  to	
  create	
  delegates	
  
•  Can	
  be	
  used	
  to	
  write	
  local	
  funcons	
  that	
  can	
  
   be	
  passed	
  as	
  arguments	
  
•  Helpful	
  for	
  wring	
  LINQ	
  query	
  expressions	
  (we	
  
   will	
  see	
  this	
  later,	
  maybe	
  J)	
  
   	
  jussi.AboutToOverload +=
       (object sender, TeacherEventArgs events) =>
       Console.WriteLine("hello");
COLLECTIONS	
  
System.Collecons	
  
•  All	
  Collecon	
  classes	
  can	
  be	
  found	
  from	
  
   System.Collecons	
  
•  Classes	
  like	
  
    –  ArrayList	
  
    –  Hashtable	
  	
  
         •  key/value	
  
    –  Queue	
  
         •  FIFO:	
  first-­‐in,	
  first-­‐out	
  
    –  SortedList	
  
         •  key/value,	
  sorted	
  by	
  the	
  keys	
  
    –  Stack	
  
         •  last-­‐in,	
  first-­‐out	
  
Example 	
  	
  
ArrayList list = new ArrayList();
list.Add("a");
list.Add("b");
list.add("c");
foreach(string s in list) { … }
Using	
  Generics	
  
ArrayList<string> list = new
ArrayList<string>();
list.Add("a");
list.Add("b");
list.add("c");
list.add(2); // Fails
foreach(string s in list) { … }
Use	
  interfaces	
  
•  Use	
  this	
  
    –  IList<string> list = new ArrayList<string>();
•  Instead	
  of	
  this	
  
    –  ArrayList<string> list = new Arraylist();
•  You	
  can	
  change	
  the	
  collecon	
  class	
  later!	
  
ABOUT	
  THREADS	
  
Threading	
  
•    Ability	
  to	
  multask	
  
•    Process	
  -­‐>	
  UI-­‐thread	
  -­‐>	
  other	
  threads	
  
•    Use	
  System.Threading	
  
•    Do	
  exercises	
  to	
  learn	
  about	
  threading!	
  

More Related Content

What's hot

Exercícios Netbeans - Vera Cymbron
Exercícios Netbeans - Vera CymbronExercícios Netbeans - Vera Cymbron
Exercícios Netbeans - Vera Cymbroncymbron
 
Graphical User Interface (GUI) - 2
Graphical User Interface (GUI) - 2Graphical User Interface (GUI) - 2
Graphical User Interface (GUI) - 2PRN USM
 
Ensure code quality with vs2012
Ensure code quality with vs2012Ensure code quality with vs2012
Ensure code quality with vs2012Sandeep Joshi
 
Chat application in java using swing and socket programming.
Chat application in java using swing and socket programming.Chat application in java using swing and socket programming.
Chat application in java using swing and socket programming.Kuldeep Jain
 
Pavel kravchenko obj c runtime
Pavel kravchenko obj c runtimePavel kravchenko obj c runtime
Pavel kravchenko obj c runtimeDneprCiklumEvents
 
Python functions
Python functionsPython functions
Python functionsToniyaP1
 
Class object method constructors in java
Class object method constructors in javaClass object method constructors in java
Class object method constructors in javaRaja Sekhar
 
Solid principles in practice the clean architecture - Droidcon Italy
Solid principles in practice the clean architecture - Droidcon ItalySolid principles in practice the clean architecture - Droidcon Italy
Solid principles in practice the clean architecture - Droidcon ItalyFabio Collini
 
iPhone Seminar Part 2
iPhone Seminar Part 2iPhone Seminar Part 2
iPhone Seminar Part 2NAILBITER
 
The Ring programming language version 1.8 book - Part 86 of 202
The Ring programming language version 1.8 book - Part 86 of 202The Ring programming language version 1.8 book - Part 86 of 202
The Ring programming language version 1.8 book - Part 86 of 202Mahmoud Samir Fayed
 
SISTEMA DE FACTURACION (Ejemplo desarrollado)
SISTEMA DE FACTURACION (Ejemplo desarrollado)SISTEMA DE FACTURACION (Ejemplo desarrollado)
SISTEMA DE FACTURACION (Ejemplo desarrollado)Darwin Durand
 
C++ Windows Forms L09 - GDI P2
C++ Windows Forms L09 - GDI P2C++ Windows Forms L09 - GDI P2
C++ Windows Forms L09 - GDI P2Mohammad Shaker
 

What's hot (20)

16 18
16 1816 18
16 18
 
Exercícios Netbeans - Vera Cymbron
Exercícios Netbeans - Vera CymbronExercícios Netbeans - Vera Cymbron
Exercícios Netbeans - Vera Cymbron
 
Graphical User Interface (GUI) - 2
Graphical User Interface (GUI) - 2Graphical User Interface (GUI) - 2
Graphical User Interface (GUI) - 2
 
Ensure code quality with vs2012
Ensure code quality with vs2012Ensure code quality with vs2012
Ensure code quality with vs2012
 
Magento code audit
Magento code auditMagento code audit
Magento code audit
 
Bot builder v4 HOL
Bot builder v4 HOLBot builder v4 HOL
Bot builder v4 HOL
 
Objective-C for Beginners
Objective-C for BeginnersObjective-C for Beginners
Objective-C for Beginners
 
Chat application in java using swing and socket programming.
Chat application in java using swing and socket programming.Chat application in java using swing and socket programming.
Chat application in java using swing and socket programming.
 
Pavel kravchenko obj c runtime
Pavel kravchenko obj c runtimePavel kravchenko obj c runtime
Pavel kravchenko obj c runtime
 
Python functions
Python functionsPython functions
Python functions
 
Class object method constructors in java
Class object method constructors in javaClass object method constructors in java
Class object method constructors in java
 
Solid principles in practice the clean architecture - Droidcon Italy
Solid principles in practice the clean architecture - Droidcon ItalySolid principles in practice the clean architecture - Droidcon Italy
Solid principles in practice the clean architecture - Droidcon Italy
 
iPhone Seminar Part 2
iPhone Seminar Part 2iPhone Seminar Part 2
iPhone Seminar Part 2
 
JavaScript
JavaScriptJavaScript
JavaScript
 
The Ring programming language version 1.8 book - Part 86 of 202
The Ring programming language version 1.8 book - Part 86 of 202The Ring programming language version 1.8 book - Part 86 of 202
The Ring programming language version 1.8 book - Part 86 of 202
 
Property-based testing
Property-based testingProperty-based testing
Property-based testing
 
Introduction to typescript
Introduction to typescriptIntroduction to typescript
Introduction to typescript
 
SISTEMA DE FACTURACION (Ejemplo desarrollado)
SISTEMA DE FACTURACION (Ejemplo desarrollado)SISTEMA DE FACTURACION (Ejemplo desarrollado)
SISTEMA DE FACTURACION (Ejemplo desarrollado)
 
C++ Windows Forms L09 - GDI P2
C++ Windows Forms L09 - GDI P2C++ Windows Forms L09 - GDI P2
C++ Windows Forms L09 - GDI P2
 
Java File
Java FileJava File
Java File
 

Similar to C# Delegates, Events, Lambda

DDD Modeling Workshop
DDD Modeling WorkshopDDD Modeling Workshop
DDD Modeling WorkshopDennis Traub
 
oops -concepts
oops -conceptsoops -concepts
oops -conceptssinhacp
 
38 object-concepts
38 object-concepts38 object-concepts
38 object-conceptsraahulwasule
 
38-object-concepts.ppt
38-object-concepts.ppt38-object-concepts.ppt
38-object-concepts.pptRavi Kumar
 
Demystifying Object-Oriented Programming - Lone Star PHP
Demystifying Object-Oriented Programming - Lone Star PHPDemystifying Object-Oriented Programming - Lone Star PHP
Demystifying Object-Oriented Programming - Lone Star PHPAlena Holligan
 
38 object-concepts (1)
38 object-concepts (1)38 object-concepts (1)
38 object-concepts (1)Shambhavi Vats
 
C# Summer course - Lecture 4
C# Summer course - Lecture 4C# Summer course - Lecture 4
C# Summer course - Lecture 4mohamedsamyali
 
Demystifying Object-Oriented Programming - ZendCon 2016
Demystifying Object-Oriented Programming - ZendCon 2016Demystifying Object-Oriented Programming - ZendCon 2016
Demystifying Object-Oriented Programming - ZendCon 2016Alena Holligan
 
import school.; import school.courses.;public class Main { p.pdf
import school.; import school.courses.;public class Main { p.pdfimport school.; import school.courses.;public class Main { p.pdf
import school.; import school.courses.;public class Main { p.pdfannaiwatertreatment
 
Hello. Im currently working on the last section to my assignment a.pdf
Hello. Im currently working on the last section to my assignment a.pdfHello. Im currently working on the last section to my assignment a.pdf
Hello. Im currently working on the last section to my assignment a.pdfirshadkumar3
 
Starting with Main.java, where I tested everythingimport College..pdf
Starting with Main.java, where I tested everythingimport College..pdfStarting with Main.java, where I tested everythingimport College..pdf
Starting with Main.java, where I tested everythingimport College..pdfaptind
 
Object Oriented JavaScript
Object Oriented JavaScriptObject Oriented JavaScript
Object Oriented JavaScriptDonald Sipe
 

Similar to C# Delegates, Events, Lambda (20)

DDD Modeling Workshop
DDD Modeling WorkshopDDD Modeling Workshop
DDD Modeling Workshop
 
oops -concepts
oops -conceptsoops -concepts
oops -concepts
 
38 object-concepts
38 object-concepts38 object-concepts
38 object-concepts
 
OOPS
OOPSOOPS
OOPS
 
38-object-concepts.ppt
38-object-concepts.ppt38-object-concepts.ppt
38-object-concepts.ppt
 
Demystifying Object-Oriented Programming - Lone Star PHP
Demystifying Object-Oriented Programming - Lone Star PHPDemystifying Object-Oriented Programming - Lone Star PHP
Demystifying Object-Oriented Programming - Lone Star PHP
 
38 object-concepts (1)
38 object-concepts (1)38 object-concepts (1)
38 object-concepts (1)
 
C# Summer course - Lecture 4
C# Summer course - Lecture 4C# Summer course - Lecture 4
C# Summer course - Lecture 4
 
Basic object oriented concepts (1)
Basic object oriented concepts (1)Basic object oriented concepts (1)
Basic object oriented concepts (1)
 
Demystifying Object-Oriented Programming - ZendCon 2016
Demystifying Object-Oriented Programming - ZendCon 2016Demystifying Object-Oriented Programming - ZendCon 2016
Demystifying Object-Oriented Programming - ZendCon 2016
 
import school.; import school.courses.;public class Main { p.pdf
import school.; import school.courses.;public class Main { p.pdfimport school.; import school.courses.;public class Main { p.pdf
import school.; import school.courses.;public class Main { p.pdf
 
Demystifying oop
Demystifying oopDemystifying oop
Demystifying oop
 
Java Class Design
Java Class DesignJava Class Design
Java Class Design
 
Hello. Im currently working on the last section to my assignment a.pdf
Hello. Im currently working on the last section to my assignment a.pdfHello. Im currently working on the last section to my assignment a.pdf
Hello. Im currently working on the last section to my assignment a.pdf
 
Design in the small
Design in the smallDesign in the small
Design in the small
 
Starting with Main.java, where I tested everythingimport College..pdf
Starting with Main.java, where I tested everythingimport College..pdfStarting with Main.java, where I tested everythingimport College..pdf
Starting with Main.java, where I tested everythingimport College..pdf
 
Delegate
DelegateDelegate
Delegate
 
Object Oriented JavaScript
Object Oriented JavaScriptObject Oriented JavaScript
Object Oriented JavaScript
 
L03 Software Design
L03 Software DesignL03 Software Design
L03 Software Design
 
Core java oop
Core java oopCore java oop
Core java oop
 

More from Jussi Pohjolainen

libGDX: Screens, Fonts and Preferences
libGDX: Screens, Fonts and PreferenceslibGDX: Screens, Fonts and Preferences
libGDX: Screens, Fonts and PreferencesJussi Pohjolainen
 
libGDX: User Input and Frame by Frame Animation
libGDX: User Input and Frame by Frame AnimationlibGDX: User Input and Frame by Frame Animation
libGDX: User Input and Frame by Frame AnimationJussi Pohjolainen
 
Intro to Building Android Games using libGDX
Intro to Building Android Games using libGDXIntro to Building Android Games using libGDX
Intro to Building Android Games using libGDXJussi Pohjolainen
 
Advanced JavaScript Development
Advanced JavaScript DevelopmentAdvanced JavaScript Development
Advanced JavaScript DevelopmentJussi Pohjolainen
 
libGDX: Simple Frame Animation
libGDX: Simple Frame AnimationlibGDX: Simple Frame Animation
libGDX: Simple Frame AnimationJussi Pohjolainen
 
libGDX: Simple Frame Animation
libGDX: Simple Frame AnimationlibGDX: Simple Frame Animation
libGDX: Simple Frame AnimationJussi Pohjolainen
 
Implementing a Simple Game using libGDX
Implementing a Simple Game using libGDXImplementing a Simple Game using libGDX
Implementing a Simple Game using libGDXJussi Pohjolainen
 
Building Android games using LibGDX
Building Android games using LibGDXBuilding Android games using LibGDX
Building Android games using LibGDXJussi Pohjolainen
 
Creating Asha Games: Game Pausing, Orientation, Sensors and Gestures
Creating Asha Games: Game Pausing, Orientation, Sensors and GesturesCreating Asha Games: Game Pausing, Orientation, Sensors and Gestures
Creating Asha Games: Game Pausing, Orientation, Sensors and GesturesJussi Pohjolainen
 
Creating Games for Asha - platform
Creating Games for Asha - platformCreating Games for Asha - platform
Creating Games for Asha - platformJussi Pohjolainen
 

More from Jussi Pohjolainen (20)

Moved to Speakerdeck
Moved to SpeakerdeckMoved to Speakerdeck
Moved to Speakerdeck
 
Java Web Services
Java Web ServicesJava Web Services
Java Web Services
 
Box2D and libGDX
Box2D and libGDXBox2D and libGDX
Box2D and libGDX
 
libGDX: Screens, Fonts and Preferences
libGDX: Screens, Fonts and PreferenceslibGDX: Screens, Fonts and Preferences
libGDX: Screens, Fonts and Preferences
 
libGDX: Tiled Maps
libGDX: Tiled MapslibGDX: Tiled Maps
libGDX: Tiled Maps
 
libGDX: User Input and Frame by Frame Animation
libGDX: User Input and Frame by Frame AnimationlibGDX: User Input and Frame by Frame Animation
libGDX: User Input and Frame by Frame Animation
 
Intro to Building Android Games using libGDX
Intro to Building Android Games using libGDXIntro to Building Android Games using libGDX
Intro to Building Android Games using libGDX
 
Advanced JavaScript Development
Advanced JavaScript DevelopmentAdvanced JavaScript Development
Advanced JavaScript Development
 
Introduction to JavaScript
Introduction to JavaScriptIntroduction to JavaScript
Introduction to JavaScript
 
Introduction to AngularJS
Introduction to AngularJSIntroduction to AngularJS
Introduction to AngularJS
 
libGDX: Scene2D
libGDX: Scene2DlibGDX: Scene2D
libGDX: Scene2D
 
libGDX: Simple Frame Animation
libGDX: Simple Frame AnimationlibGDX: Simple Frame Animation
libGDX: Simple Frame Animation
 
libGDX: Simple Frame Animation
libGDX: Simple Frame AnimationlibGDX: Simple Frame Animation
libGDX: Simple Frame Animation
 
libGDX: User Input
libGDX: User InputlibGDX: User Input
libGDX: User Input
 
Implementing a Simple Game using libGDX
Implementing a Simple Game using libGDXImplementing a Simple Game using libGDX
Implementing a Simple Game using libGDX
 
Building Android games using LibGDX
Building Android games using LibGDXBuilding Android games using LibGDX
Building Android games using LibGDX
 
Android Threading
Android ThreadingAndroid Threading
Android Threading
 
Creating Asha Games: Game Pausing, Orientation, Sensors and Gestures
Creating Asha Games: Game Pausing, Orientation, Sensors and GesturesCreating Asha Games: Game Pausing, Orientation, Sensors and Gestures
Creating Asha Games: Game Pausing, Orientation, Sensors and Gestures
 
Creating Games for Asha - platform
Creating Games for Asha - platformCreating Games for Asha - platform
Creating Games for Asha - platform
 
Intro to Asha UI
Intro to Asha UIIntro to Asha UI
Intro to Asha UI
 

Recently uploaded

The Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfThe Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfSeasiaInfotech2
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 
Vector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesVector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesZilliz
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr LapshynFwdays
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clashcharlottematthew16
 

Recently uploaded (20)

The Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfThe Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdf
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 
Vector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesVector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector Databases
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clash
 

C# Delegates, Events, Lambda

  • 1. C#:  Delegates,  Events  and   Lambda   Jussi  Pohjolainen   Tampere  University  of  Applied  Sciences  
  • 2. About  Callbacks   •  Callback  methods  can  be  implemented  in  C#   using  delegates,  events  and  lambda   •  Callback  method?     –  When  buGon  is  clicked,  a  method  is  called  (calls  back   a  method  you  have  implemented)   •  Delegate  type  “points”  to  a  method  or  a  list  of   methods   –  Event  will  help  you  to  build  callback  mechanism   •  Lambda  is  anonymous  method  and  provides   simplified  approach  working  with  delegates  
  • 3. JavaScript:  Callback   function doSomething(integer, someFunction) { var i = 0, s = 0; for(i = 0; i<integer; i = i + 1) { s += integer; } // callback! someFunction(s); } function callBackFunction(result) { print('result is: ' + result); } function main() { doSomething(5000, callBackFunction); } main();
  • 4. Java  7:  Anonymous  methods  and   callbacks   // Kind of hard? button.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { // do something } }) // Note: Java 8 will have lambda
  • 5. Obj-­‐C:  Selectors  and  Callbacks   - (void) testSelectors { SEL variable; variable = @selector(animate); [self methodWithSelectorAsArgument: variable]; } - (void) methodWithSelectorAsArgument: (SEL) argument { [self performSelector:argument]; } - (void) animate { ... }
  • 6. Delegate   •  Delegate  type  holds   –  Address  of  the  method  on  which  it  makes  calls   –  Parameters  of  the  method   –  Return  type  of  the  method   •  Works  both  asynchronously  and   synchronously.  Simplifies  things,  no  need  for   Thread  object.  Let’s  see  this  later  
  • 7. Example   // Following delegate type can point to whatever // method as long as it's returning int and it has two // parameters. public delegate int Something(int a, int b); // This will generate a following class! Lot of methods // also deriving from MulticastDelegate and Delegate (base class // for MulticastDelegate) sealed class Something : System.MulticastDelegate { public int Invoke(int x, int y); public IAsyncResult BeginInvoke(int x, int y, AsyncCallback cb, object state); public int EndInvoke(IAsyncResult result); }
  • 8. using System; public delegate int Something(int a, int b); class MyMath { public int Add(int a, int b) { return a + b; } } class MyMain { public static void Main() { MyMath m = new MyMath(); Something delegateObject = new Something(m.Add); Console.WriteLine( delegateObject.Invoke(5,5) ); // Calls Invoke! Console.WriteLine( delegateObject(5,5) ); } }
  • 9. using System; public delegate int Something(int a, int b); class MyMath { public static int Add(int a, int b) { return a + b; } } class MyMain { public static void Main() { Something delegateObject = new Something(MyMath.Add); // Calls Invoke! Console.WriteLine( delegateObject(5,5) ); } }
  • 10. class MyMain { public static void Main() { Something delegateObject = new Something(MyMath.Add); PrintInformation(delegateObject); } // All delegates inherite Delegate class public static void PrintInformation(Delegate delObj) { // Remember that delegate may hold number of methods! foreach(Delegate d in delObj.GetInvocationList()) { // Result: Int32 Add(Int32, Int32) Console.WriteLine(d.Method); } } }
  • 12. class Teacher { // A new inner class is created here! The class inherits // System.MulticastDelegate // This can point to whatever class that is void and one string // argument. This could be also outer-class. public delegate void TeacherHandler(string msg); // Declare an attribute type of the new class. private TeacherHandler listOfHandlers; // Helper method for assigning the attribute public void RegisterWithListener(TeacherHandler methodToCall) { listOfHandlers = methodToCall; } public bool teacherIsBoring { get; set; } public void teach() { // If teacher is not boring if(!teacherIsBoring) { // And there are someone listening if(listOfHandlers != null) { // Send message to the listener. listOfHandlers("C# is cool!"); } } } }
  • 13. using System; class MyMain { public static void Main() { Teacher jussi = new Teacher(); // instantiate inner class object jussi.RegisterWithListener(new Teacher.TeacherHandler(OnTeachEvent)); jussi.teacherIsBoring = false; jussi.teach(); } // Since teacher is not boring and we are listening, // this method is called public static void OnTeachEvent(string m) { Console.WriteLine("Important message from teacher!"); Console.WriteLine(m); } }
  • 15. // Helper method for assigning the attribute public void RegisterWithListener(TeacherHandler methodToCall) { if(listOfHandlers == null) { listOfHandlers = methodToCall; } else { Delegate.Combine(listOfHandlers, methodToCall); } } … Teacher jussi = new Teacher(); // instantiate inner class object jussi.RegisterWithListener(new Teacher.TeacherHandler(OnTeachEvent1)); jussi.RegisterWithListener(new Teacher.TeacherHandler(OnTeachEvent2)); jussi.teacherIsBoring = false; jussi.teach();
  • 16. // Helper method for assigning the attribute public void RegisterWithListener(TeacherHandler methodToCall) { // And even more easier! listOfHandlers += methodToCall; } … Teacher jussi = new Teacher(); // instantiate inner class object jussi.RegisterWithListener(new Teacher.TeacherHandler(OnTeachEvent1)); jussi.RegisterWithListener(new Teacher.TeacherHandler(OnTeachEvent2)); jussi.teacherIsBoring = false; jussi.teach();
  • 18. class MyMain { public static void Main() { Teacher jussi = new Teacher(); // instantiate inner class object jussi.RegisterWithListener(new Teacher.TeacherHandler(OnTeachEvent1)); Teacher.TeacherHandler listener; jussi.RegisterWithListener(listener = new Teacher.TeacherHandler(OnTeachEvent2)); jussi.teacherIsBoring = false; jussi.teach(); jussi.UnRegisterWithListener(listener); jussi.teach(); } .. // Helper method for assigning the attribute public void UnRegisterWithListener(TeacherHandler methodToCall) { listOfHandlers -= methodToCall; }
  • 20. Method  Group  Conversion   •  In  the  previous  example,  we  created  object   –  Teacher.TeacherHandler   •  You  don't  have  to  do  this!   •  Method  group  conversion!   –  Direct  method  name  is  converted  to  a  delegate   object  
  • 21. Method  Group  Conversion   public static void Main() { Teacher jussi = new Teacher(); jussi.RegisterWithListener(OnTeachEvent1); jussi.RegisterWithListener(OnTeachEvent2); jussi.teacherIsBoring = false; jussi.teach(); jussi.UnRegisterWithListener(OnTeachEvent2); jussi.teach(); }
  • 23. Simplify  Registering   •  The  previous  example  had  methods  like   –  public  void  RegisterWithListener(TeacherHandler   methodToCall)   –  public  void   UnRegisterWithListener(TeacherHandler   methodToCall)   •  To  simplify  this,  we  can  use  events!  
  • 24. class Teacher { private int workHoursPerDay = 0; public delegate void TeacherHandler(string msg); // No register or unregister methods! // When using events, two hidden methods are generated: // add_AboutToOverload // remove_AboutToOverLoad public event TeacherHandler AboutToOverload; public event TeacherHandler MentallyDead; public void teach() { workHoursPerDay++; if(workHoursPerDay >= 4 && workHoursPerDay < 6) { if(AboutToOverload != null) { AboutToOverload("TOO MUCH WORK FOR ME! Workhours = " + workHoursPerDay); } } else if(workHoursPerDay >= 6) { if(MentallyDead != null) { MentallyDead("CANNOT WORK ANYMORE, BITCH ABOUT THIS! Workhours = " + workHoursPerDay); } } } }
  • 25. class MyMain { public static void Main() { Student pekka = new Student(); pekka.Name = "Pekka"; Supervisor jaska = new Supervisor(); jaska.Name = "Jaska"; Teacher jussi = new Teacher(); jussi.AboutToOverload += pekka.listen; jussi.AboutToOverload += jaska.listen; jussi.MentallyDead += jaska.listen; jussi.teach(); jussi.teach(); jussi.teach(); jussi.teach(); jussi.teach(); jussi.teach(); jussi.teach(); jussi.teach(); } }
  • 26. class Student { public string Name {get; set;} public void listen(string m) { Console.WriteLine(Name + " listening to teacher msg = " + m); } } class Supervisor { public string Name {get; set;} public void listen(string m) { Console.WriteLine(Name + " listening to teacher msg = " + m); } }
  • 28. class Student { public string Name {get; set;} // Listener here get information: // 1) who is the sender? // 2) more information about the event public void listen(object sender, TeacherEventArgs events) { Console.WriteLine(Name + " listening to teacher msg = " + events.msg); } } class Supervisor { public string Name {get; set;} public void listen(object sender, TeacherEventArgs events) { Console.WriteLine(Name + " listening to teacher msg = " + events.msg); } }
  • 29. // Implement own custom event! public class TeacherEventArgs : EventArgs { public readonly string msg; public TeacherEventArgs(string message) { msg = message; } } // And use it class Teacher { private int workHoursPerDay = 0; public delegate void TeacherHandler(object sender, TeacherEventArgs e); … public void teach() { … AboutToOverload(this, new TeacherEventArgs("TOO MUCH WORK …")); … }
  • 31. public class TeacherEventArgs : EventArgs { public readonly string msg; public TeacherEventArgs(string message) { msg = message; } } class Teacher { private int workHoursPerDay = 0; /* public delegate void TeacherHandler(object sender, TeacherEventArgs e); public event TeacherHandler AboutToOverload; public event TeacherHandler MentallyDead; */ // Now we can use the EventHandler class. Notice that there is no // need for the delegate anymore! public event EventHandler<TeacherEventArgs> AboutToOverload; public event EventHandler<TeacherEventArgs> MentallyDead;
  • 32. class MyMain { public static void Main() { Student pekka = new Student(); pekka.Name = "Pekka"; Supervisor jaska = new Supervisor(); jaska.Name = "Jaska"; Teacher jussi = new Teacher(); // Now we can use the EventHandler class! jussi.AboutToOverload += new EventHandler<TeacherEventArgs>(pekka.listen); jussi.AboutToOverload += jaska.listen; jussi.MentallyDead += jaska.listen;
  • 33. Anonymous  Delegate  Methods   Teacher jussi = new Teacher(); jussi.AboutToOverload += delegate (object send, TeacherEventArgs events) { Console.WriteLine("anonymous delegate method 1!"); }; jussi.AboutToOverload += delegate { Console.WriteLine("anonymous delegate method 2!"); };
  • 35. Lambda  Expressions   •  Lambda  expression  is  an  anonymous  funcon   that  you  can  use  to  create  delegates   •  Can  be  used  to  write  local  funcons  that  can   be  passed  as  arguments   •  Helpful  for  wring  LINQ  query  expressions  (we   will  see  this  later,  maybe  J)    jussi.AboutToOverload += (object sender, TeacherEventArgs events) => Console.WriteLine("hello");
  • 37. System.Collecons   •  All  Collecon  classes  can  be  found  from   System.Collecons   •  Classes  like   –  ArrayList   –  Hashtable     •  key/value   –  Queue   •  FIFO:  first-­‐in,  first-­‐out   –  SortedList   •  key/value,  sorted  by  the  keys   –  Stack   •  last-­‐in,  first-­‐out  
  • 38. Example     ArrayList list = new ArrayList(); list.Add("a"); list.Add("b"); list.add("c"); foreach(string s in list) { … }
  • 39. Using  Generics   ArrayList<string> list = new ArrayList<string>(); list.Add("a"); list.Add("b"); list.add("c"); list.add(2); // Fails foreach(string s in list) { … }
  • 40. Use  interfaces   •  Use  this   –  IList<string> list = new ArrayList<string>(); •  Instead  of  this   –  ArrayList<string> list = new Arraylist(); •  You  can  change  the  collecon  class  later!  
  • 42. Threading   •  Ability  to  multask   •  Process  -­‐>  UI-­‐thread  -­‐>  other  threads   •  Use  System.Threading   •  Do  exercises  to  learn  about  threading!