Best practices: When should I use a delegate in .NET?

.net, c#, delegates

Solution

Delegates are useful when you need to tell another piece of code how to do something. Events are the simplest example - separating the event (something happened) from how to handle it. Other examples are some common iterative operations, such as a custom find:

List<Foo> foos = new List<Foo>();
foos.Find(delegate(Foo foo)
    {
        if(foo.CustomProperty.Contains("special value"))
        {
            return false;
        }
        return true;
    });

The above is a totally arbitrary example but makes the point that you can separate the what (iterating and running a "find" criteria) from the how (how to determine whether something is found).

Problem

Possible Duplicates: Delegate Usage : Business Applications Where do I use delegates? Hi, I'm new to the concept of a delegate in .NET - I haven't really used them yet and think they are probably there for a good reason - when should I be using a delegate? Examples are very welcome.

Original source

Related problems