Friday, May 16, 2014

PCL Tips and Tricks: List.ForEach

The introduction of Portable Class Libraries, PCL, considerably facilitates the sharing of functionality across managed Microsoft and Xamarin platforms. I am very enthusiastic about the PCL concept, and I have ported several .NET Framework open source projects to Portable Class Libraries. Along the way I have stumbled across various issues of making .NET Framework source code PCL compliant. In this mini-series I'll share my experiences and workarounds to facilitate the transfer to PCL for other developers.

The List<T>.ForEach method is available on all managed Microsoft platforms, except one: Windows 8 (f.k.a. Windows Store or Metro). Possibly as a consequence of this, it is also not available in the Portable Class Libraries, not even when Windows 8 is not targeted.

The exact reasons for leaving out List<T>.ForEach from Windows 8 and PCL is unknown to me, but maybe the library maintainers want to discourage developers from using this method since it allows for side effects in a functional context (thanks Vagif Abilov for pointing this out). Fortunately, there is a simple replacement that should work practically always: use foreach instead!

So, instead of:

List<string> strs = ...;
strs.ForEach(str => DoSometing(str));

Use this:

List<string> strs = ...;
foreach (var str in strs) { DoSomething(str); }

I recently looked into the Clipper project, which is an open source library for clipping and offseting 2D polygons, available in several languages. I examined the C# source code, and it turned out that the author had used the List<T>.ForEach construct in his code. This was in fact the only issue preventing the C# Clipper code from being truly portable. Therefore, as a feature request I asked him to use foreach instead. This feature request was later implemented, and it is now possible to take the entire clipper.cs file and include it in any Portable Class Library.

Here are a few links about List<T>.ForEach vs. foreach:

No comments:

Post a Comment