Reputation: 1097
I see increasing use of the delegate types offered in the System namespace (Action<T>
; Predicate<T>
etc). As these are delegates, my understanding is that they should be used where we have traditionally used delegates in the past (asynchronous calls; starting threads, event handling etc). Is it just preference or is it considered practice to use these delegate types in scenarios such as the below; rather than using calls to methods we have declared (or anonymous methods):
public void MyMethod()
{
Action<string> action = delegate(string userName
{
try
{
XmlDocument profile = DataHelper.GetProfile(userName);
UpdateMember(profile);
}
catch (Exception exception)
{
if (_log.IsErrorEnabled) _log.ErrorFormat(exception.Message);
throw (exception);
}
};
GetUsers().ForEach(action);
}
At first, I found the code less intuitive to follow than using declared or anonymous methods. I am starting to code this way, and wonder what the view are in this regard. The example above is all within a method. Is this delegate overuse?
Upvotes: 3
Views: 270
Reputation: 1500805
For a simple foreach
loop, I would prefer the normal language construct - see this blog post for Eric Lippert's view. I think the use of a delegate here is somewhat gratuitous.
In other cases - particularly with LINQ - it makes a lot of sense.
Delegates are a nice way of allowing specialization without the overhead of declaring and implementing an interface or deriving from a type in order to override methods... but everything in moderation, of course. If you've got several methods to implement (and you really want to specify behaviour for all of them) then an interface makes more sense. If you're genuinely creating a specialized type then deriving and overriding make sense. If you're wanting a strategy pattern, however, then delegates work very neatly.
Upvotes: 4