What’s The Point Of Delegates In .NET?
A coworker just asked me this question – what’s the point of delegates in .NET? My answer was very short and one that he had not found online: to delay execution of a method.
Consider this: if you pass a Method2 as a parameter to Method1, Method2 is evaluated immediately and the result is passed into Method1.
public class SomeObject
{
public void Method1(int someValue)
{
//... code here
}
}
...
someObject.Method1(anotherObject.Method2());
Additionally, Method2 must have a return value (not void) so that the value returned from Method2 can be passed as the parameter of Method1.
With a delegate, though, we get method pointers that can be used to delay the execution of the method in question until it’s needed (if at all). We can also get rid of the requirement for a return value and we can pass values that were created by the host method, into the delegate method.
public class SomeObject
{
public void Method1(Action<int> someAction)
{
//.. do some stuff here
int aValue = GetTheValueFromSomeWhere();
someAction(aValue);
//... do some more here
}
}
public class AnotherObject
{
public void Method2(int aValue)
{
//do something that is dependent on aValue, here.
int i = aValue + 1; // or anything else that needs aValue.
}
}
FYI – Action (void return; with many parameterized variations) is a delegate that is build into .NET 3.5, along with Func
Most .NET developers have used delegates without realizing it, too. The event system in .NET is nothing more than a multi-cast delegate – a delegate that points to more than one method – with a special signature and syntax (depending on the language being used).
There’s a lot of good use for delegates. And like any other tools, there’s a lot of bad uses. Take the time to learn what they are, how they work, and where they can be beneficial.