Thread: C# Delegates

    #1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jan 2016
    Posts
    2
    Rep Power
    0

    C# Delegates


    Hello everyone,

    I have got a little question to someone a bit more experienced with programing in C# than I am...

    First of all, im new to programming and for some time I have been learning how to code in C#,
    quickly I relised programming is not a thing you can just pick up overnight and the honeymoon and excitement
    of learning how to code dissapeared. However I did not give up and continued working, I really like the feeling
    when something you couldnt get your head around finally clicks and you know how it works... Unforunately I think
    I've hit a brick wall on my way... and that wall is Delegates... I just really dont get how they work... and why would
    would you use them? In my understanding its just another way of calling functions...

    Could someone kindly explain to me in simple examples how and when to use delegates ?

    Thank you!.
  2. #2
  3. Lord of the Dance
    Devshed Specialist (4000 - 4499 posts)

    Join Date
    Oct 2003
    Posts
    4,109
    Rep Power
    2010
    Have you looked at this explanation: https://msdn.microsoft.com/en-us/library/ms173171.aspx?
  4. #3
  5. Forgotten Moderator
    Devshed Supreme Being (6500+ posts)

    Join Date
    Mar 2007
    Location
    Washington, USA
    Posts
    15,971
    Rep Power
    9615
    Have you ever wanted to pass a function as an argument to another function? Consider something like sorting a list: the sorting itself is pretty obvious, "if this is less than that then it comes first", but how do you decide what is less than another thing? It's easy with numbers, and it's not difficult with strings, but what about more complex data like objects?
    csharp Code:
    public class Person
    {
     
    	public string Name { get; set; }
    	public int Age { get; set; }
     
    }

    How do you sort a person? Well, the most obvious ways would be by name or by age. Normally you would have to write two different sorting methods.
    csharp Code:
    public static IList<Person> SortByAge(IEnumerable<Person> People)
    {
    	// ...
    }
     
    public static IList<Person> SortByName(IEnumerable<Person> People)
    {
    	// ...
    }


    That's really annoying. The only difference between the two is how they decide what is "less than" another: sorting by age compares the Age while sorting by name compares the Name.
    csharp Code:
    public static int CompareAge(Person A, Person B)
    {
    	return A.Age - B.Age;
    }
     
    public static int CompareName(Person A, Person B)
    {
    	return A.Name.CompareTo(B.Name);
    }

    What if you could pass one of those methods to a general-purpose sorter? They both have the same signature: first argument is a Person, second argument is a Person, method returns an int. So
    csharp Code:
    public delegate int ComparePerson(Person A, Person B);

    Then
    csharp Code:
    public static IList<Person> Sort(IEnumerable<Person> People, ComparePerson Comparer)


    Then you notice that ComparePerson happens to look exactly like a Comparison<Person>, which means you can use List<T>.Sort instead of writing your own Sort method.
    csharp Code:
    List<Person> people = new List<Person>() {
    	new Person { Name = "George", Age = 67 },
    	new Person { Name = "John", Age = 90 },
    	new Person { Name = "Thomas", Age = 83 }
    };
    people.Sort(Person.CompareAge); // George, Thomas, John
    people.Sort(Person.CompareName); // George, John, Thomas


    Going one step further, CompareAge and CompareName are really simple so you could do away with the methods and use lambdas (anonymous functions) instead.
    csharp Code:
    people.Sort((A, B) => A.Age - B.Age);
    people.Sort((A, B) => A.Name.CompareTo(B.Name));

    Comments on this post

    • moment93 agrees
    • MrFujin agrees : Thans for sorting this out. :D
    Last edited by requinix; January 11th, 2016 at 03:54 PM. Reason: fixing bug with A.Name.CompareTo(B)
  6. #4
  7. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jan 2016
    Posts
    2
    Rep Power
    0
    Originally Posted by requinix
    Have you ever wanted to pass a function as an argument to another function? Consider something like sorting a list: the sorting itself is pretty obvious, "if this is less than that then it comes first", but how do you decide what is less than another thing? It's easy with numbers, and it's not difficult with strings, but what about more complex data like objects?
    csharp Code:
    public class Person
    {
     
    	public string Name { get; set; }
    	public int Age { get; set; }
     
    }

    How do you sort a person? Well, the most obvious ways would be by name or by age. Normally you would have to write two different sorting methods.
    csharp Code:
    public static IList<Person> SortByAge(IEnumerable<Person> People)
    {
    	// ...
    }
     
    public static IList<Person> SortByName(IEnumerable<Person> People)
    {
    	// ...
    }


    That's really annoying. The only difference between the two is how they decide what is "less than" another: sorting by age compares the Age while sorting by name compares the Name.
    csharp Code:
    public static int CompareAge(Person A, Person B)
    {
    	return A.Age - B.Age;
    }
     
    public static int CompareName(Person A, Person B)
    {
    	return A.Name.CompareTo(B);
    }

    What if you could pass one of those methods to a general-purpose sorter? They both have the same signature: first argument is a Person, second argument is a Person, method returns an int. So
    csharp Code:
    public delegate int ComparePerson(Person A, Person B);

    Then
    csharp Code:
    public static IList<Person> Sort(IEnumerable<Person> People, ComparePerson Comparer)


    Then you notice that ComparePerson happens to look exactly like a Comparison<Person>, which means you can use List<T>.Sort instead of writing your own Sort method.
    csharp Code:
    List<Person> people = new List<Person>() {
    	new Person { Name = "George", Age = 67 },
    	new Person { Name = "John", Age = 90 },
    	new Person { Name = "Thomas", Age = 83 }
    };
    people.Sort(Person.CompareAge); // George, Thomas, John
    people.Sort(Person.CompareName); // George, John, Thomas


    Going one step further, CompareAge and CompareName are really simple so you could go away with the methods and use lambdas (anonymous functions) instead.
    csharp Code:
    people.Sort((A, B) => A.Age - B.Age);
    people.Sort((A, B) => A.Name.CompareTo(B));
    I cant stress enough how helpful your explanation was!
    I wish they have explained it in the book, just as you did.

    Thank you!

IMN logo majestic logo threadwatch logo seochat tools logo