what is main reason for introducing delegates and also it is solution for which type problems.i like to know that problem.Thanks in advance
+5
A:
You can mostly think of delegates as being like interfaces with a single method. So in places where a language without delegates (such as Java) would use an interface, it makes sense to have a delegate.
Delegates have these benefits over interfaces:
- The implementation can be private, whereas methods implementing interfaces have to be public in Java. (C# has explicit interface implementation as well.)
- You can implement multiple delegates in a single class, or even the same delegate type multiple times
- The framework and language have additional support for delegates:
- Combining them together (and removing them)
- A pub/sub framework (events)
- Background invocation using the thread pool (BeginInvoke etc)
- Lambda expressions and anonymous methods make them easy to create "inline"
- Expression trees, representing the logic of an expression in data rather than IL
Delegates are typically used for:
- Event handling, e.g. in GUIs
- Providing "small" pieces of behaviour, e.g. the filters and projections in LINQ
- Callbacks for asynchronous programming
Think of them as a way of encapsulating a single piece of behaviour, and see where that leads you.
Jon Skeet
2010-06-25 06:07:38