Skip to content

Lecture No. 08

Dated: 29-04-2025

delegate

A delegate is a reference to a method.

using System;

// this is the delegate declaration
public delegate int Comparer (object obj1, object obj2);

public class Name {
    public string firstname = null;
    public string lastname = null;

    public Name (string first, string last) {
        Firstname = first;
        Lastname = last;
    }

    // this is the delegate method handler
    public static int CompareFirstNames (object name1, object name2) {
        string n1 = ((Name)name1).firstname;
        string n2 = ((Name)name2).firstname;
        if (String.Compare(n1, n2) > 0) {
            return 1;
        }
        else if (String.Compare(n1, n2) < 0) {
            return -1;
        }
        else {
            return 0;
        }
    }

    public override string ToString () {
        return firstname + " " + lastname;
    }
}

class SimpleDelegate {
    Name[] names = new Name[5];

    public SimpleDelegate () {
        names[0] = new Name("Joe", "Mayo");
        names[1] = new Name("John", "Hancock");
        names[2] = new Name("Jane", "Doe");
        names[3] = new Name("John", "Doe");
        names[4] = new Name("Jack", "Smith");
    }

    static void Main (string[] args) {
        SimpleDelegate sd = new SimpleDelegate();
        // this is the delegate instantiation
        Comparer cmp = new Comparer(Name.CompareFirstNames);
        Console.WriteLine("\nbefore Sort: \n");
        sd.PrintNames();
        // observe the delegate argument
        sd.Sort(cmp);
        Console.WriteLine("\nafter Sort: \n");
        sd.PrintNames();
    }

    // observe the delegate parameter
    public void Sort (Comparer compare) {
        object temp;
        for (int i = 0; i < names.Length; i++) {
            for (int j = i; j < names.Length; j++) {
                // using delegate "compare" just like
                // a normal method
                if (compare(names[i], names[j]) > 0) {
                    temp = names[i];
                    names[i] = names[j];
                    names[j] = (Name)temp;
                }
            }
        }
    }

    public void PrintNames () {
        Console.WriteLine("Names: \n");
        foreach (Name name in names) {
            Console.WriteLine(name.ToString());
        }
    }
}
using System;
using System.Drawing;
using System.Windows.Forms;

// custom delegate
public delegate void StartDelegate ();

class EventDemo : Form {
    // custom event
    public event StartDelegate StartEvent;

    public EventDemo () {
        Button clickMe = new Button();
        clickMe.Parent = this;
        clickMe.Text = "Click Me";
        clickMe.Location = new Point(
            (ClientSize.Width - clickMe.Width) / 2,
            (ClientSize.Height - clickMe.Height) / 2);
        // an event handler delegate is assigned
        // to the button's Click event
        clickMe.Click += new EventHandler(OnClickMeClicked);
        // our custom "StartDelegate" delegate is assigned
        // to our custom "StartEvent" event.
        StartEvent += new StartDelegate(OnStartEvent);
        // fire our custom event
        StartEvent();
    }

    // this method is called when the "clickMe" button is pressed
    public void OnClickMeClicked (object sender, EventArgs ea) {
        MessageBox.Show("You Clicked My Button!");
    }

    // this method is called when the "StartEvent" Event is fired
    public void OnStartEvent () {
        MessageBox.Show("I Just Started!");
    }

    static void Main (string[] args) {
        Application.Run(new EventDemo());
    }
}
  • Setup Options:
    • Add references to:
      • System.Drawing.dll
      • System.Windows.Forms.dll
    • OR create a new Windows Forms Project
  • Class Inheritance:
    • Inherits from Form
    • Gains all Form features: title bar, minimize/maximize/close buttons, borders, etc.
  • Starting the App:
    • Call Application.Run(yourFormObject);
  • Event Handling:
    • Use += to register event handlers
    • Click event uses pre-defined .NET EventHandler delegate
    • Define a method matching the delegate signature (e.g., OnClickMeClicked)

Exception Handling

using System;
using System.IO;

class trycatchdemo {
    static void Main (string[] args) {
        try {
            File.OpenRead("nonexistentfile");
        }
        catch (Exception ex) {
            Console.WriteLine(ex.ToString());
        }
    }
}