SitePoint Sponsor

User Tag List

Results 1 to 8 of 8
  1. #1
    SitePoint Member
    Join Date
    Jan 2009
    Location
    Texas
    Posts
    17
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    C# Delegate help

    Hello all,

    I have been using and studying C#. Why am I confused about Delegates or don't quite understand them.

    Does anyone know where I can go or read about Delegates? I want to use them effectively and have a good understanding of the.

    Thanks,
    Edward

  2. #2
    Non-Member
    Join Date
    Mar 2009
    Location
    Ontario
    Posts
    39
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    A delegate is a type that references a method. Once a delegate is assigned a method, it behaves exactly like that method. The delegate method can be used like any other method, with parameters and a return value, as in this example:

    C# Copy Code
    public delegate int PerformCalculation(int x, int y);

    Any method that matches the delegate's signature, which consists of the return type and parameters, can be assigned to the delegate. This makes is possible to programmatically change method calls, and also plug new code into existing classes. As long as you know the delegate's signature, you can assign your own delegated method.

    This ability to refer to a method as a parameter makes delegates ideal for defining callback methods. For example, a sort algorithm could be passed a reference to the method that compares two objects. Separating the comparison code allows the algorithm to be written in a more general way.

    Read more here: http://msdn.microsoft.com/en-us/libr...71(VS.80).aspx

  3. #3
    SitePoint Member
    Join Date
    Jan 2009
    Location
    Texas
    Posts
    17
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Nice... Interesting. I'll take a look. I appreciate the valuable information.

  4. #4
    Non-Member
    Join Date
    Mar 2009
    Location
    Ontario
    Posts
    39
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thanks, If you face difficulty in understanding do come back. MSDN is a good source to learn C# practically.

  5. #5
    SitePoint Member
    Join Date
    Jan 2009
    Location
    Texas
    Posts
    17
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I guess I'm just so used to creating methods only. So, I can have methods and delegates right?

  6. #6
    Non-Member
    Join Date
    Mar 2009
    Location
    Ontario
    Posts
    39
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    right, you can have both.

  7. #7
    SitePoint Author silver trophybronze trophy
    wwb_99's Avatar
    Join Date
    May 2003
    Location
    Washington, DC
    Posts
    10,625
    Mentioned
    4 Post(s)
    Tagged
    0 Thread(s)
    You can't have one without the other. A good way to think of delegates is they are a function-typed variable, with the typing being the signature of the function. Oh, and you can do all sorts of really neat stuff with them.

  8. #8
    ALT.NET - because we need it silver trophybronze trophy dhtmlgod's Avatar
    Join Date
    Jul 2001
    Location
    Scotland
    Posts
    4,836
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Delegates are awesome and really add alot to the framework, expecially combinded with lambdas.

    Since 3.5 the framework has featured three built in delgates: Predicate, Action and Func.

    Predicates take an input and return a boolean, it's designed to save the need to use a Func to create the same.

    The Action is designed to be used with delegates that don't return a value, like so:

    Code Csharp:
    .......
    IList<User> users = userRepository.RetrieveAllUsers();
    users.Each(item => item.SetSomething(someValue))
    .......
    public void Map<T>(this IEnumerable<T> items, Action<T> action)
    {
       foreach (var item in items)
       {
          action(item);
       }
    }

    Func's are for delegates that return a value:
    Code Csharp:
    Func<Guid, User> retrieveUser = id => userRepository.RetrieveForId(id);
    LoadUser(retrieveUser);
    ....
    public void LoadUser(Func<Guid, User> retrieveUser)
    {
       Guid id = GettingTheIdFromSomethingElse();
       User user = retrieveUser(id);
     
       return user;
    }

    Think of delegates as a way of enabling closures in .NET.

    Another nice thing with delegates, is you can use them with Linq Expression for stronly typed static reflection:
    Code Csharp:
    public static MethodInfo GetMethod<T>(Expression<Func<T, object>> expression)
            {
                MethodCallExpression methodCall = (MethodCallExpression)expression.Body;
                return methodCall.Method;
            }
    .....
    MethodInfo info = ReflectionHelper.GetMethod<HomeController>(controller => controller.Index());
    Trace.Write(info.Name); // Will print Index
    I use this in a number of places, can really help reducing the number of magic strings, especially in a Web UI:
    Code Csharp:
    <%= HtmlHelper.TextBoxFor<UserViewModel>(user => user.Username).WithLabel()%>
    creates:
    Code Csharp:
    <lable for="user-Username">Username:</label><input type="text" id="user-Username" name="user-Username" />
    THe beauty of this is that it suport refactoring. If I renamed the Username property, it will be renamed here!

    Delegates are a powerful addition to your toolbox, I highly recommend getting to know them well and use them to their full ability.


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •