Fun with C#: ForEach for everyone!

Whenever possible, I like using a ForEach method, instead of a for-each block. Take the code below for example:

The iteration part could be rewritten like so:

Or, even better, since the AddToPizza method takes in one parameter with the same type of the items we’re iterating over…

The iteration could simply look like this:

However, not every thing we iterate has the ForEach method. For example, regular arrays don’t. So, if our items source looked like the one below, we wouldn’t have a ForEach method:

So how do we get a ForEach method that works on Lists, Collections, Arrays, etc? Just create the extension method on IEnumerable<T>, like so:

Make sure to import the namespace for your extension methods (using statement) wherever you’re trying to use them!

Advertisements
  1. Leave a comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: