Reputation: 30514
After learning about the Action delegate in C# I've been looking for ways I can best use it in my code. I came up with this pattern:
Action<string> DoSomething = (lSomething) =>
{
// Do something
};
DoSomething("somebody");
DoSomething("someone");
DoSomething("somewhere");
If I were to have used a traditional loop, it would look something like this:
List<string> lSomeList = new List<string>();
lSomeList.Add("somebody");
lSomeList.Add("someone");
lSomeList.Add("somewhere");
foreach (string lSomething in lSomeList)
{
// Do something
}
Are there any appreciable differences between the two? To me they look equally easy to understand and maintain, but are there some other criteria I might use to distinguish when one might be preferred over the other?
Upvotes: 1
Views: 883
Reputation: 171188
There is an advantage to the first pattern that does not come up with loops. Example:
Action<string> DoSomething = (lSomething) =>
{
// Do something
};
DoSomething("somebody");
if (b) DoSomething("somebody2");
else while (F()) DoSomething("somebody3")
...
So you see the lambda version is more flexible because it can be invoke in mutiple places, not only in one place.
Upvotes: 0
Reputation: 1500375
If you need to be able to pass the action from one piece of code to another, it's really nice to wrap it up in a delegate.
If you need the same action in slightly different contexts within the same method, a delegate is one option - although extracting it into a different method may make more sense, depending on the situation.
Usually I would just go for executing the code directly though. The example you've given isn't particularly realistic IMO - usually you'd have a list either way and either call List<T>.ForEach
or use a plain foreach
loop - at which point I'd favour the foreach
loop for the same reasons that Eric Lippert gives in the blog post Anthony linked to.
Upvotes: 4
Reputation: 126834
The fact that you have three method calls versus a loop and a single method (or simply a loop body) would be enough to make me reconsider.
Semi-related, perhaps read this blog and see if that gives you a different perspective. http://blogs.msdn.com/ericlippert/archive/2009/05/18/foreach-vs-foreach.aspx
Upvotes: 3