Wrox Programmer Forums
|
BOOK: Beginning Visual C# 2010
This is the forum to discuss the Wrox book Beginning Visual C# 2010 by Karli Watson, Christian Nagel, Jacob Hammer Pedersen, Jon D. Reid, Morgan Skinner, ; ISBN: 9780470502266
Welcome to the p2p.wrox.com Forums.

You are currently viewing the BOOK: Beginning Visual C# 2010 section of the Wrox Programmer to Programmer discussions. This is a community of software programmers and website developers including Wrox book authors and readers. New member registration was closed in 2019. New posts were shut off and the site was archived into this static format as of October 1, 2020. If you require technical support for a Wrox book please contact http://hub.wiley.com
 
Old November 12th, 2011, 04:14 AM
Authorized User
 
Join Date: Sep 2011
Posts: 24
Thanks: 7
Thanked 0 Times in 0 Posts
Default Delegates

This is an example for delegates from outside the text.
Code:
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());
        }
    }
}
1)First a delegate is declared:
public delegate int Comparer(object obj1, object obj2);


2)Then delegate method handler is defined:

3)In main() an instance of delegate is created
Comparer cmp = new Comparer(Name.CompareFirstNames);

This will refer the method declared in Name class.


4)Then we called sd.sort(cmp)

5)sort method is defined to accept one parameter
of type comparer.

Then what happens to the code.
From where the
public static int CompareFirstNames(object name1, object name2)
method gets 2 object parameters.
Please explain it simply as I am a beginner.
 
Old November 12th, 2011, 08:09 PM
Registered User
 
Join Date: Nov 2011
Posts: 2
Thanks: 0
Thanked 0 Times in 0 Posts
Default

Sounds as though you want to know what the String.Compare method does. You could debug your code and step through, placing break points where you want to analyze the data, and/or read the Microsoft explanation H E R E
 
Old November 12th, 2011, 10:09 PM
Friend of Wrox
 
Join Date: Sep 2010
Posts: 171
Thanks: 0
Thanked 14 Times in 14 Posts
Default

if you're only a beginner, you're trying to consume too many concepts with that piece of code, in my opinion. Lol, I'm no expert, but that piece of code encapsulates many concepts that you should take in individual doses, concepts such as Hierarchy and Inheritance, Casting Objects to Arrays, Looping, Delegates...

Your question is sufficiently vague that it (to me) indicates you're trying to wrap you head around too many concepts at once.

However, since you titled this thread with the word "delegate", coupled with you saying "5)sort method is defined to accept one parameter
of type comparer", I'll take a stab at helping you out.

You know how you can pass in parameters to a method right? Like an integer or a string. Well, you can also pass in another method as a parameter. That's what a delegate is: another method passed in as a parameter.

Think of it this way:

You have a class called Janitor()

If you call Janitor.Work() with no parameters, the janitor will sweep, mop, dust, check for leaky faucets, etc.

But sometimes you'll want to give the janitor specific instructions, such as "someone just dropped a glass container full of juice on aisle 5, can you go clean it up please?"

In other words, you're not just asking your janitor to work, you're giving him a specific set of directions. That's what a delegate is. You're calling the Janitor.Work() method while passing the specific task you want him/her to perform.

Luckily, you've overloaded the Janitor.Work() method with one that accepts a delegate (a specific set of directions, such as "cleanup on aisle 5").

So in code (and I won't get the syntax right here as i'm also a beginner) it would look something like this:

Code:
// the delegate
delegate void JanitorInstructions (object Work1, object Work2, int AisleNumber);



public class Janitor
{
    private int aisleNumer;

    public Work(JanitorInstructions ji)
       {
           //do the janitor's work here
        }
          

    public void DealWithBrokenGlass() { }
    public void DealWithJuiceOnFloor() {}
}

static void Main()
{
//instantiate the janitor
Janitor janitor = new Janitor();

//instantiate the delegate (what you want the janitor to do)
JanitorInstructions ji = new JanitorInstructions(janitor.DealWithBrokenGlass, janitor.DealWithJuiceOnFloor, 5);

//ask the janitor to get it done
janitor.Work(ji);
}

Since it's the blind leading the blind, if that didn't get at answering your question, let me know, we'll go from there. I know the concept of delegates well enough to put the concept in your head if that's what you're after.

mike
The Following User Says Thank You to mtranchi For This Useful Post:
arun_babu_a (November 14th, 2011)
 
Old November 14th, 2011, 01:38 AM
Authorized User
 
Join Date: Sep 2011
Posts: 24
Thanks: 7
Thanked 0 Times in 0 Posts
Default Thanks

Friends thanks for the help
What make me confused was
Code:
 compare(names[i], names[j]) > 0 .
I didn't put enough time on this line and that makes things went wrong.





Similar Threads
Thread Thread Starter Forum Replies Last Post
Delegates naresh0407 ASP.NET 4 General Discussion 1 August 23rd, 2010 06:27 AM
Help with delegates mike_remember ASP.NET 1.0 and 1.1 Professional 2 November 7th, 2006 12:33 AM
Delegates RalphJr C# 2005 1 April 29th, 2006 08:06 AM
Delegates pramos.21d C# 1 April 11th, 2006 03:43 AM
Help with Delegates mike_remember ASP.NET 1.0 and 1.1 Basics 4 October 4th, 2005 07:32 AM





Powered by vBulletin®
Copyright ©2000 - 2020, Jelsoft Enterprises Ltd.
Copyright (c) 2020 John Wiley & Sons, Inc.