Links

Categories

Tags


« | Main | »

Delegates

By Jewe | October 29, 2012

import stdlib;
using stdlib;

// define a delegate type for our ForEach() function
delegate Printer(string item);

// function that calls a delegate for every element of an array
function ForEach(string[] values, Printer func)
{
    for (int i = 0; i < values.length; i++)
    {
        func(values[i]);
    }
}

// a function compatible with the Printer delegate
function PrintElement(string s)
{
    println(s);
}

function string main(const string[] args)
{
    // create an array of strings
    string[] names = { "Judy", "Christopher", "Helen", "James", "Sandra", "Rick", "Elisabeth" };

    // call 'PrintElement' for every item in the array
    ForEach(names, PrintElement);

    return null;
}

Topics: code examples | Comments Off on Delegates

Comments are closed.