Delegates - PowerPoint PPT Presentation

1 / 34
About This Presentation
Title:

Delegates

Description:

C# does not differentiate between checked and unchecked exceptions ... All exceptions are 'unchecked' and are propagated if not handled locally ... – PowerPoint PPT presentation

Number of Views:63
Avg rating:3.0/5.0
Slides: 35
Provided by: natheerk
Category:

less

Transcript and Presenter's Notes

Title: Delegates


1
Delegates
  • Simplest description type-safe function pointers
  • Declaring a delegate defines a class that derives
    from System.MulticastDelegate, which derives from
    System.Delegate

2
Delegates
  • Sometimes useful to pass methods as arguments to
    other methods
  • Delegates are sets of references to methods
  • Delegate objects can be passed to methods
    methods can then invoke the methods the delegate
    objects refer to
  • Delegates that contain one method are known as
    singlecast delegates and are created or derived
    from class Delegate
  • Delegates that contain multiple methods are known
    as multicast delegates and are created or derived
    from class MulticastDelegate

3
Delegates
  • Delegates must be declared before use
  • A delegate declaration specifies the parameters
    and return type of the methods the delegate can
    refer to
  • Methods who can be referred to by a delegate,
    must have the same signature as the delegate
  • Delegate instances can then be created to refer
    to a method(s)
  • Once a delegate instance is created, the method
    it refers to can be invoked

4
Delegates
  • Delegates maintain a list of methods to be called
    when the delegate is invoked.
  • To insure type safety, the signature (return type
    and arguments) of acceptable callback
  • methods is specified when the delegate class is
    defined.
  • We instantiate a delegate by "wrapping" the
    callback method.
  • We can add methods to the callback chain or
    remove methods from the chain.

5
Using Delegate
  • First must declare one.
  • The delegates declaration specifies a method
    header (parameters and return value).
  • Methods whose references will be contained within
    a delegate object must have the same method
    header as that defined in the delegate
    declaration.
  • Second create methods that have this signature.
  • The third step is to create a delegate instance
    that contains a reference to that method.
  • Finally we can invoke the method reference that
    it contains. We show this process in our
  • next example.

6
  • using System
  • delegate int MathOp(int x, int y) //Declare
    delegate type
  • class Class1
  • static void Main(string args)
  • MathOp f1 new MathOp(Class1.Add)
    //Instantiate
  • MathOp f2 new MathOp(Class1.Mult)//delegates
  • Console.WriteLine(DoSomeMath(f1, 2, 3))
  • Console.WriteLine(DoSomeMath(f2, 2, 3))
  • public static int DoSomeMath(MathOp fn, int x,
    int y)
  • return fn(x, y) //Invoke the delegate
  • public static int Add(int a, int b)
  • return a b

7
(No Transcript)
8
  • class DemoClass
  • private string name
  • private int number
  • public DemoClass(string str, int x)
  • name str
  • number x
  • public void ShowMyName()
  • Console.WriteLine("My name is " this.name)
  • public void ShowMyNumber()
  • Console.WriteLine("My number is "
    this.number)

9
  • delegate void DemoOp() //Declare delegate type
  • static void Main(string args)
  • //Create some objects
  • DemoClass dc1 new DemoClass("Demo 1", 1)
  • DemoClass dc2 new DemoClass("Demo 2", 2)
  • //Declare an empty delegate
  • DemoOp demoDel null
  • //Append a method to list
  • demoDel new DemoOp(dc1.ShowMyNumber)
  • //Append another one
  • demoDel new DemoOp(dc2.ShowMyName)
  • //Invoke the delegate
  • demoDel()

10
(No Transcript)
11
  • class DemoClass
  • private string name
  • private int number
  • public DemoClass(string str, int x)
  • name str
  • number x
  • public void ShowMyName()
  • Console.WriteLine("My name is " this.name)
  • public void ShowMyNumber()
  • Console.WriteLine("My number is "
    this.number)

What is "this" when the method is called via
a delegate?
12
  • delegate void DemoOp() //Declare delegate type
  • static void Main(string args)
  • //Create some objects
  • DemoClass dc1 new DemoClass("Demo 1", 1)
  • DemoClass dc2 new DemoClass("Demo 2", 2)
  • //Declare an empty delegate
  • DemoOp demoDel null
  • //Append a method to list
  • demoDel new DemoOp(dc1.ShowMyNumber)
  • //Append another one
  • demoDel new DemoOp(dc2.ShowMyName)
  • //Invoke the delegate
  • demoDel()

13
Delegates Behind the Scenes
14
The Microsoft .NET Event Model
  • Events provide a way for one object to notify
    another object that something has happened
  • Events use the delegate mechanism for invoking
    callback functions
  • Visual Studio simplifies the use of events with
    GUI elements

15
Events and Delegates
16
Events and Delegates
17
Events and Delegates
18
  • public class InfoEventArgs EventArgs
  • private DateTime date
  • public InfoEventArgs(DateTime date)
  • this.date date
  • public DateTime Date
  • get return date
  • public delegate void InfoEventHandler(Object
    sender,
  • InfoEventArgs args)

19
  • public class InfoProvider
  • public event InfoEventHandler InfoEvent
  • public InfoProvider()
  • public void Start()
  • . . .

Callback functions of this type can be called
when the event fires.
20
  • class InfoProvider
  • public event InfoEventHandler InfoEvent
  • . . .
  • public void Start()
  • DateTime start
  • TimeSpan span
  • start DateTime.Now
  • do
  • span DateTime.Now - start
  • while(span.Seconds lt 2)
  • if (InfoEvent ! null)
  • DateTime date DateTime.Now
  • InfoEventArgs args new InfoEventArgs(date)
  • InfoEvent(this, args)

21
  • class Class1
  • static void Main(string args)
  • InfoProvider ip new InfoProvider()
  • ip.InfoEvent new InfoEventHandler(GetDay)
  • ip.InfoEvent new InfoEventHandler(GetTime)
  • ip.Start()
  • public static void GetDay(Object sender,
    InfoEventArgs e)
  • Console.WriteLine(e.Date.DayOfWeek)
  • public static void GetTime(Object sender,
    InfoEventArgs e)
  • Console.WriteLine(e.Date.Hour ""
    e.Date.Minute)

22
Events and Delegates
23
Exceptions
  • public void SomeMethod(...)
  • File file new File("Readme.txt")
  • .
  • .
  • .
  • file.Close()

What happens if the file doesnt exist?
What happens if an error occurs in here?
24
Part of the exception hierarchy
25
Exceptions the general idea
  • try
  • some code that might throw an exception
  • more code
  • catch (most specific exception)
  • handle the exception
  • catch (less specific exception)
  • handle the exception
  • catch (any exception)
  • handle the exception
  • finally

26
  • try
  • some code that might throw an exception
  • more code
    No exception thrown
  • catch (most specific exception)
  • handle the exception
  • catch (less specific exception)
  • handle the exception
  • catch (any exception)
  • handle the exception
  • finally

27
  • try
  • some code that might throw an exception
  • more code
  • catch (most specific exception)
  • handle the exception
  • catch (less specific exception)
  • This exception thrown
  • handle the exception
  • catch (any exception)
  • handle the exception
  • finally

28
  • try
  • some code that might throw an exception
  • more code
  • catch (most specific exception)
  • handle the exception
  • catch (less specific exception)
  • This exception thrown
  • handle the exception
  • return
  • catch (any exception)
  • handle the exception
  • finally

29
  • try
  • some code that might throw an exception
  • more code
  • catch (most specific exception)
  • handle the exception
  • catch (less specific exception)
  • This exception thrown
  • handle the exception
  • throw
  • catch (any exception)
  • handle the exception
  • finally

30
  • using System.IO
  • public void SomeMethod(...)
  • File file null
  • try
  • file new File("Readme.txt")
  • more code
  • catch (FileNotFoundException e)
  • Console.WriteLine("File " e.FileName " not
    found")
  • catch (Exception e)
  • Console.WriteLine(e)
  • finally

31
Exceptions
  • In a catch block, you can
  • Rethrow the same exception, notifying code higher
    in the call stack
  • Throw a different exception, giving additional
    information to code higher in the call stack
  • Handle the exception and fall out the bottom of
    the catch block

32
Exceptions
  • Remember that
  • Exceptions are not always "errors"
  • Exceptions are not always infrequent
  • Sometimes it's best not to catch an exception
    where it occurs
  • There is a performance hit for exceptions

33
Exceptions
  • public void SomeMethod(...)
  • File file null
  • try
  • file new File("Readme.txt")
  • more code
  • finally
  • if (file ! null)
  • file.Close()

Since there is no catch block, the exception is
propagated to the caller
34
Exceptions Similarities to Java
  • C does not differentiate between checked and
    unchecked exceptions
  • Java insists that checked exceptions be handled
    or thrown.
  • In C, no exception handling is necessary
  • C has no throws keyword. All exceptions are
    "unchecked and are propagated if not handled
    locally
  • When an exception is caught, it is not necessary
    to assign the exception object to a variable
    name, and the throw keyword by itself rethrows
    the same exception
  • catch (Exception)
  • . . .
  • throw
Write a Comment
User Comments (0)
About PowerShow.com