Func<T> based Generic List Initializers
A couple of weeks ago I was writing some code to initialize List<T> but my technique was very verbose and it seemed to be a distraction from what I was trying to do. Plus it seemed that every one else was writing about getting their func on.
So I looked back at some code that Nick Parker had written:
And tweaked it to initialize a list:
Now I can initialize a list like this:
Just for the record the Func initialization above could handle much more complex scenarios if needed. My usage is very simple.
Another variation on this is to create an extension method that does the same initialization like this:
And here is how you would use the extension method version:
Thanks to Nick Parker for some suggestions as I was working on this.
Something I would like to figure out is how to do this based on IEnumerable instead of IList. If you have ideas regarding implementing this on IEnumerable please add them as comments.
Also, if you want to see where I was using this, pull down the subversion source here: http://subversion.assembla.com/svn/solon-tools/trunk/Puzzles