Archived

This topic is now archived and is closed to further replies.

I hate to bother you guys again, but could someone explain delegates to me?

This topic is 5133 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Okay, here is the code the tutorial I am following is using as an example:
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());
        }
    }
} 
Well, Ive tried to follow it, but I have no idea what is going on. Im not even sure where to tell you where I am having problems, becauase I am not really sure. I guess what is giving me problems is the delegate method handler. I see what it is doing, but I dont see how it is doing it (what does ojb1 and 2 refer to exactly?). I am also not understanding how and why to use a delegate, or even when it is supposed to be used. Im sorry to be such a nuisance. Any help is greatly appreciated. Thanks. [edited by - The Orange Peanut on November 29, 2003 12:05:56 PM]

Share this post


Link to post
Share on other sites
If you''ve used C or C++ before, it''s like a function pointer except more flexible.

Here''s a simpler example:



// delegate declaration

public delegate void MyDelegate(int foo);

// example function

public static void MyDelegateHandler(int foo)
{
Console.WriteLine("Number: " + foo);
}

public static void Main(String[] args)
{
MyDelegate dele = new MyDelegate(MyDelegateHandler);

dele(5);
}



Share this post


Link to post
Share on other sites
Alright, more about delegate... I wrote this little program to test my understanding of delegates. Its nothing complicated at all, but what the hey.


using System;

class Execution
{
public delegate int Foo(int Bar);

//delegate handler

public static int FooHandle(int Bar)
{
Bar = Bar + 10;
return Bar;
}

public static void Main()
{
Foo newfoo = new Foo(FooHandle);
Console.WriteLine("Answer = {0}", newfoo(4));
Console.WriteLine("Answer = {0}", newfoo(10));
Console.ReadLine();
}
}


Well, I understand how this works, I think. The first line is declaring a delegate, its name and parameters. The second function is the delegate handler, which is what the delegate does when it is called. In the Main() function, I instanciate a delege by writing Foo newfoo = new Foo(FooHandle). What this does is say "Im a delegate, and Im when you use me as a function Im going to do whatever is in FooHandle". Well, on down the page, I do newfoo(4) and the output is what I expected. Did I get everything right?

Well, here is a new problem. In the original post I made, there is a delegate that has object parameters. What are these exactly, and how are they used?

Thanks.

Share this post


Link to post
Share on other sites
The Object class is the base class of all classes. If you create a class that isn''t derived from any other one then Object automatically is added as its base class. Object has methods such as ToString(),GetType(),etc... in it.

Share this post


Link to post
Share on other sites